更新时间:2023-12-01 18:08:40
有点盲目,因为你没有包括什么属性实体
有。但您应该有一个关系的属性为 CustomerGroups
。只需将该属性设置为要与之相关的组。例如,这将创建一个新的组名称foo bar,并将实体与该组关联。
Flying a little blind since you didn't include what properties entity
has. But you should have a property for the relationship to CustomerGroups
. Just set that property with the groups you want to be related to. For example, this would create a new Group name "foo bar" and relate the entity to that group.
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
表中插入一个关系。
If the relationship is setup correctly, EF will automatically insert a record into CustomerGroups
and insert a relationship into the CustomerInGroups
table.
编辑:
如果您尝试向现有的客户添加一个现有的 CustomerGroup
您首先需要从数据库中获取 CustomerGroup
,然后将其添加到您要插入的Customer实体。
If you're trying to add an existing CustomerGroup
to a new Customer. You'll want to get the CustomerGroup
from the database first, then add it to the Customer entity you're inserting.
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;
}