调用 SaveChanges() 时 EF6 重复记录

EF6 Duplicate records when calling SaveChanges()

如标​​题所示,当我调用 SaveChanges()

时记录重复

我尝试了所有的解决方案,尝试了我所知道的和我能找到的

这是我的上下文和模型。

public partial class EllesiaDB : DbContext
{
    public EllesiaDB()
        : base("EllesiaDB")
    {
    }


    public DbSet<AccountModel> Accounts { get; set; }
    public DbSet<CharacterModel> Characters { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        //Account=>Many(Character)
        modelBuilder.Entity<AccountModel>().HasMany(x => x.Characters)
            .WithRequired(x => x.Account).HasForeignKey(x => x.AccountId);
        base.OnModelCreating(modelBuilder);
    }
}
[Table("Accounts")]
public class AccountModel
{
    [Key]
    public int Id { get; set; }
    public string Username { get; set; }
    public string Password { get; set; }
    public virtual ICollection<CharacterModel> Characters { get; set; }
}
[Table("Characters")]
public class CharacterModel
{
    [Key]
    public int Id { get; set; }
    public virtual AccountModel Account { get; set; }
    public int AccountId { get; set; }
    public string Name { get; set; } = "";
}

这是我将字符保存到数据库的函数

private CharacterModel m_CharacterModel = new CharacterModel();
public AccountModel Account => m_CharacterModel.Account;

public void SaveToDB()
{
    using (var db = new EllesiaDB())
    {
        var isUpdate = db.Characters.Where(x => x.Id == Id).Select(x=>x).Any();

        db.Entry(m_CharacterModel).State = isUpdate ? EntityState.Modified : EntityState.Added;
        db.Entry(Account).State = EntityState.Modified;
        db.SaveChanges();
    }
}

db 将像下面这样工作。 而且调用前也没有重复的记录 SaveChanges().

先把简存到账号1

Accounts
Id | Username | Password
0    testid     testpw
1    testid1    testpw1

Characters
Id | AccountId | Name
0    0           Parah
1    1           Jane

秒将森存入账号1

Accounts
Id | Username | Password
0    testid     testpw
1    testid1    testpw1

Characters
Id | AccountId | Name
0    0           Parah
1    1           Jane
2    1           Mori
3    1           Jane

账号1第三次存Rain

Accounts
Id | Username | Password
0    testid     testpw
1    testid1    testpw1

Characters
Id | AccountId | Name
0    0           Parah
1    1           Jane
2    1           Mori
3    1           Jane
4    1           Rain
5    1           Jane
6    1           Mori
7    1           Jane

由于 CharacterModel 是 AccountModel 的子项,如果启用延迟加载,您可能 inserting/updating CharacterModel 两次。在 inserting/updating AccountModel 之前检查 AccountModel 内嵌套的 ICollection of Characters。如果集合已填充,那就是你的问题。禁用延迟加载或删除第二个 insert/update

这 2 个模型是相关联的,因此如果操作正确,您只需插入主模型而不是子模型。 但是您的主模型必须包含带有 .Include() 的子模型或启用延迟加载以保存链接的两个模型。