【发布时间】:2016-02-06 12:32:45
【问题描述】:
我有 3 张桌子,
1) 客户(ID、姓名、bla bla)
2) 客户组(GroupId、GroupName)
3) CustomerInGroups (CustomerId, GroupId)
using (var context = DataObjectFactory.CreateContext())
{
context.Customers.Add(entity);
context.SaveChanges();
return entity.Id;
}
如何将记录添加到 CustomerInGroups? EntityFramework 不会为这种多对多映射表生成实体
编辑:
Customer 和 CustomerGroups 中的 Id 列都设置为自动递增。
所以在我的 CustomersGroup 表中,我有
Id Name
----------------------------
1 Normal
2 VIP
我尝试按照其中一位海报的建议这样做:
entity.CustomerGroups = new List<CustomerGroup>
{
new CustomerGroup {Id = 2 }
};
context.Customers.Add(entity);
context.SaveChanges();
return entity.Id;
但是,当我这样做时,不是像这样在映射表中创建记录:
CustomerId GroupId
----------------------------
1 2
我得到的是
CustomerInGroups
CustomerId GroupId
----------------------------
1 3
CustomerGroups
Id Name
----------------------------
1 Normal
2 VIP
3 NULL
它实际上在我的 CustomerGroups 表中创建了另一个条目,这不是我想要的
【问题讨论】:
-
当您将客户分配到组时,实体框架是否不会自动为您更新连接表,反之亦然?如果联接没有有效负载(即仅外键的联接),则无需创建单独的实体
标签: c# .net entity-framework many-to-many