c# - 实体框架插入到具有现有寄存器的多对多实例中,创建重复的寄存器
问题描述
好吧,我有这个配置:
- 项目有 0 个或多个组和 0 个或多个用户(表GroupsItem和UsersItem)
- 组和用户在 0 个或多个Items中
- 组和用户在应用程序中独立创建
这就是问题所在:当我尝试插入一个新项目时,我必须指出它的组和用户是什么(已经存在)。当它发生时,表格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
是一种返回 a 的方法,该方法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();
推荐阅读
- windows - 在 Md5deep 结果上运行 findstr 并仅输出目录
- javascript - 无法从下拉列表中获取用户输入
- haskell - 将浮点列表字符串转换为 Haskell 中的浮点列表列表
- elasticsearch - Elasticsearch:使用一个索引与多个索引时性能有何不同
- c++ - Visual Studio C++ 寻找不存在的 obj,link1104
- angularjs - AngularJS 和 WebAPI 中的 IdentityServer 角色/权限
- html - CSS / HTML中的字体不会改变?
- c# - OpenQA.Selenium.Remote.RemoteWebDriver.UnpackAndThrowOnError 在 WebElement 提交单击
- c++ - 将 opencv_world400.lib 和 opencv_world400d.lib 添加到依赖项中,仍然出现 LNK2001 错误
- azure - API 管理设置策略给出错误 id 为“servicefabric”的后端找不到