[英]Entity Framework Insert into a many-to-many instance with already existing registers, creating duplicated registers
好吧,我有这个配置:
问题出在这里:当我尝试插入新项目时,我必须指出其组和用户 (已经存在)是什么。 发生这种情况时,表GroupsItem , UsersItem和Item已正确填充,但是我在Groups和Users处有重复的寄存器。
这是我的代码摘要:
项目 :
public class Item {
public ICollection<Groups> GROUPS{ get; set; }
public ICollection<Users> USERS{ get; set; }
}
组 :( 用户具有相同的结构)
public class Groups{
public ICollection<Item> ITEM { get; set; }
}
插入新项目 :
public static void InsertingItem(){
Item example = new Item(){
GROUPS = AlreadyExistingGroup()
}
using (myDbContext db = new myDbContext()){
db.ITEMS.Add(example);
db.SaveChanges();
}
}
就是这样。 AlreadyExistingGroup
是一种返回List<Groups>
的方法,该方法填充有数据库中已经存在的组,将这些组带入的方法是一个将单个组带入一个函数的函数,但多次调用:
public static Groups FetchGroups(int id) {
try {
using (myDbContext db = new myDbContext ()) {
Groups group = db.GROUPS.Where(x => x.CODGROUP == id).FirstOrDefault();
return group;
}
} catch (Exception e) {
return null;
}
}
我做错了什么,导致组和用户的寄存器重复?
使用我们在注释中出现的正确解决方案来编辑我的答案:
问题在于代码中的两个不同的DbContext:
public static void InsertingItem(){
Item example = new Item(){
// DbContext #1 is created in this method
GROUPS = AlreadyExistingGroup();
}
// And this is DbContext #2
using (myDbContext db = new myDbContext()){
db.ITEMS.Add(example);
db.SaveChanges();
}
}
解决方法是对新项目的查找和插入使用相同的DbContext
。 例:
public static void InsertingItem(){
using (myDbContext db = new myDbContext()){
Item example = new Item(){
// refactor the AlreadyExistingGroup method to accept a DbContext, or to move
// the code from the method here
GROUPS = AlreadyExistingGroup(dbContext) ;
}
db.ITEMS.Add(example);
db.SaveChanges();
}
}
如果我正确地理解了您的设置,我认为您希望网上论坛仅具有一个父项引用。
public class Groups{ public Item ITEM { get; set; } // }
另外,我并没有拒绝或批评,只是建议:在询问EF问题时也张贴模型配置会很有帮助。 因为...好吧... EF可能很挑剔。 又名:
modelBuilder.Entity<Group>() .HasMaxLength(50) .WhateverElseYouConfigure();
根据您对注释的澄清,在新的Item
实体中设置它们时,似乎正在使用未跟踪(未附加)的Group
和User
实体。 将Item
实体添加到Items
DbSet
,将其作为EntityState.Added
进行跟踪。 EF将传播Item
实体的对象图,并遇到未跟踪的相关实体(即您已设置的User
和Group
集合),它将跟踪以前未跟踪的实体EntityState.Added
,从而在数据中插入新记录存储这些实体。
要解决此问题,请手动将这些相关实体附加为EntityState.Unchanged
。 例如,您可以使用DbContext.AttachRange方法
db.AttachRange( existingGroups );
或者,您也可以通过DbContext.Entry方法附加每个实体
db.Entry( existingGroup ); // this tracks the entity as Unchanged
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.