首页 > 解决方案 > 调用 SaveChanges() 时 EF6 重复记录

问题描述

就像标题一样,我打电话时记录是重复的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()

首先将 Jane 保存在帐号 1 中

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

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

第二次将 Mori 保存在帐号 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

标签: c#entity-frameworkentity-framework-6

解决方案


由于 CharacterModel 是 AccountModel 的子模型,如果启用了延迟加载,您可能会插入/更新 CharacterModel 两次。在插入/更新 AccountModel 之前,请检查 AccountModel 中嵌套的 ICollection 字符。如果集合已填充,那是您的问题。禁用延迟加载或删除第二个插入/更新


推荐阅读