Search code examples
c#entity-frameworkentity-framework-6

EF6 Duplicate records when calling SaveChanges()


Like in title, records are duplicated when i calling SaveChanges()

I tried all of solutions, tries as i know and as i can found

here is my Context and Models.

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; } = "";
}

and this is my function for save character to db

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 will be work like below. and also there is no duplicated records before the call SaveChanges().

first save Jane in account number 1

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

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

second save Mori in account number 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

third save Rain in account number 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
4    1           Rain
5    1           Jane
6    1           Mori
7    1           Jane

Solution

  • Those 2 models are linked so you only have to insert the master model and not the child if you do things correctly. But your master model must contain the child model with .Include() or with lazy loading enabled for saving both models linked.