I have a simple ExternalAccount
entity:
namespace Domain
{
public class ExternalAccount
{
public Guid Id { get; set; }
public string APIKey { get; set; }
}
}
and an AppUser
entity that has a one-to-many relationship with the ExternalAccount
using Microsoft.AspNetCore.Identity;
namespace Domain
{
public class AppUser : IdentityUser
{
public ICollection<ExternalAccount> ExternalAccounts { get; set; } = new List<ExternalAccount>();
}
}
My DataContext
class is also pretty straightforward:
using Domain;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
namespace Persistence
{
public class DataContext : IdentityDbContext<AppUser>
{
public DataContext(DbContextOptions options) : base(options)
{
}
public DbSet<ExternalAccount> ExternalAccounts { get; set; }
}
}
Now for simplicity I have a method that contains the following:
var user = await _context.Users.Include(p => p.ExternalAccounts).FirstOrDefaultAsync(x => x.UserName == "Bob");
if (user == null) return null;
ExternalAccount account = new ExternalAccount
{
Id = "08186b29-e603-4cc8-9575-47b237775274",
APIKey = "some long text here",
};
user.ExternalAccounts.Add(account);
var result = await _context.SaveChangesAsync() > 0;
After hitting the last line I'm getting a
"statusCode": 500,
"message": "The database operation was expected to affect 1 row(s), but actually affected 0 row(s); data may have been modified or deleted since entities were loaded. See http://go.microsoft.com/fwlink/?LinkId=527962 for information on understanding and handling optimistic concurrency exceptions.",
While debugging if I hover over user.ExternalAccounts.Add(account);
it looks like the account has been added.
Any idea what could be the problem here?
CodePudding user response:
Before saving your changes in your dbcontext, you need to update the users table:
await _context.Users.Update(user);
Call the above-mentioned piece before SaveChangesAsync() attempt.
CodePudding user response:
Your class ExternalAccount might need a reference to the AppUser class:
namespace Domain
{
public class ExternalAccount
{
public Guid Id { get; set; }
public string APIKey { get; set; }
public int UserId { get; set; }
public virtual AppUser User { get; set; }
}
}
Then you can map it inside your dbcontext:
modelBuilder.Entity<ExternalAccount>(entity =>
{
entity.HasOne(ea => ea.User)
.WithMany(u => u.ExternalAccount)
.HasForeignKey(ea => ea.UserId);
});