首页 > 解决方案 > 实体框架插入到具有现有寄存器的多对多实例中,创建重复的寄存器

问题描述

好吧,我有这个配置:

这就是问题所在:当我尝试插入一个新项目时,我必须指出它的用户是什么(已经存在)。当它发生时,表格GroupsItemUsersItemItem被正确填充,但我在GroupsUsers有重复的寄存器。

这是我总结的代码:

项目

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

我做错了什么导致组和用户重复注册?

标签: c#entity-frameworklinq

解决方案


使用我们在评论中得出的正确解决方案编辑我的答案:

问题在于代码中的两个不同的 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();


推荐阅读