gpt4 book ai didi

c# - Entity Framework 将记录添加到多对多映射表中

转载 作者:可可西里 更新时间:2023-11-01 09:07:26 27 4
gpt4 key购买 nike

我有 3 个表,

1)客户(身份证,姓名,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;
}

关于c# - Entity Framework 将记录添加到多对多映射表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15262974/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com