c# - 调用 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
解决方案
由于 CharacterModel 是 AccountModel 的子模型,如果启用了延迟加载,您可能会插入/更新 CharacterModel 两次。在插入/更新 AccountModel 之前,请检查 AccountModel 中嵌套的 ICollection 字符。如果集合已填充,那是您的问题。禁用延迟加载或删除第二个插入/更新
推荐阅读
- python - 从python代码执行字节码.pyc?
- mysql - Mysql 删除和时间戳
- javascript - 创建对象复制旧的
- ios - 在 UISearchController 下添加水平滚动过滤器选项
- oracle - dba_hist_sqlstats 中的 elapsed_time_delta 不是实际的查询运行时间?
- r - ggplot - 使用重新排序的数据保留轴标签着色
- ios - 使用 IOS 11 Drag&Drop 功能拖动单元格时,UICollectionViewFlowLayout 中究竟发生了什么?
- wordpress - get_posts 不返回多个帖子类型
- android - 找不到带有哈希字符串“27.0.3”的目标 Android Studio 3.1.3
- javascript - 当用户在 KendoNumericTextbox 中输入十进制字符时显示错误