【发布时间】:2021-09-29 17:04:27
【问题描述】:
和标题一样,当我调用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
第三次将 Rain 保存在帐号 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
【问题讨论】:
标签: c# entity-framework entity-framework-6