[英]Entity Framework adding record into many to many mapping table
我有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;
}
如何在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表中创建了另一个条目,这不是我想要的
因为你没有包含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;
}
如果关系设置正确,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;
}
如果您尝试将现有客户分配给_existing组并假设CustomerGroup对象公开ICollection,请执行以下操作:
(var context = DataObjectFactory.CreateContext())
{
context.Customers.Add(entity);
var group = context.CustomerGroups.Find(2); // or however you retrieve the existing group
group.Customers.Add(entity);
context.SaveChanges();
return entity.Id
}
Find()方法是通过Id查找的实体框架代码优先(DbContext)方式。 我不记得我的头脑中“正确”的ObjectContext方式,但是.Single(g => g.Id == 2)也可以。
理想情况下,您可以更好地了解您的实体是如何映射的,这样我们就知道您如何关联您的实体。
除了@ Steven-v的回答之外,如果您之前已经获取了客户组并且您不想再从db中获取它们,那么您也可以将它们附加到上下文中。
foreach (var c in customer.CustomerGroups)
{
_db.CustomerGroups.Attach(c);
}
_db.Customer.Add(customer);
_db.SaveChanges();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.