实体框架将记录添加到多对多的映射表中

Nul*_*nce 10 .net c# many-to-many entity-framework

我有3张桌子,

1)客户(Id,Name,bla bla)

2)CustomerGroups(GroupId,GroupName)

3)CustomerInGroups(CustomerId,GroupId)

using (var context = DataObjectFactory.CreateContext())
{                
    context.Customers.Add(entity);
    context.SaveChanges();
    return entity.Id;
}
Run Code Online (Sandbox Code Playgroud)

如何在CustomerInGroups中添加记录?EntityFramework不会为这样的多对多映射表生成实体

编辑:

Customer和CustomerGroups中的Id列都设置为自动增量.

所以在我的CustomersGroup表中,我有

Id          Name
----------------------------
1           Normal
2           VIP
Run Code Online (Sandbox Code Playgroud)

我尝试这样做,因为其中一张海报建议:

entity.CustomerGroups = new List<CustomerGroup>
{
    new CustomerGroup {Id = 2 }
};
context.Customers.Add(entity);
context.SaveChanges();
return entity.Id;
Run Code Online (Sandbox Code Playgroud)

但是,当我这样做时,而不是像这样在映射表中创建一条记录:

CustomerId          GroupId
----------------------------
1                   2
Run Code Online (Sandbox Code Playgroud)

我得到的是

CustomerInGroups
    CustomerId          GroupId
    ----------------------------
    1                   3

CustomerGroups
    Id          Name
    ----------------------------
    1           Normal
    2           VIP
    3           NULL
Run Code Online (Sandbox Code Playgroud)

它实际上在我的CustomerGroups表中创建了另一个条目,这不是我想要的

Ste*_*n V 8

因为你没有包含什么属性而有点失明entity.但你应该有一个属性的关系CustomerGroups.只需使用您想要关联的组设置该属性即可.例如,这将创建一个新的组名"foo bar",并将该实体与该组相关联.

using (var context = DataObjectFactory.CreateContext())
{
    entity.CustomerGroups = new List<CustomerGroup> { GroupName = "Foo bar" };
    context.Customers.Add(entity);
    context.SaveChanges();
    return entity.Id;
}
Run Code Online (Sandbox Code Playgroud)

如果关系设置正确,EF将自动插入记录CustomerGroups并在CustomerInGroups表中插入关系.

编辑:

如果您尝试将现有内容添加CustomerGroup到新客户.您将CustomerGroup首先从数据库中获取数据,然后将其添加到您要插入的Customer实体中.

using (var context = DataObjectFactory.CreateContext())
{
    var customerGroups = context.CustomerGroups.Where(...).ToList(); // get your CustomerGroup object(s) here, and ensure it's enumerated with ToList()
    entity.CustomerGroups = customerGroups;
    context.Customers.Add(entity);
    context.SaveChanges();
    return entity.Id;
}
Run Code Online (Sandbox Code Playgroud)