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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15262974/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 16:09:30  来源:igfitidea点击:

Entity Framework adding record into many to many mapping table

c#.netentity-frameworkmany-to-many

提问by Null Reference

I have 3 tables,

我有3张桌子,

1) Customer (Id, Name, bla bla)

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

2) CustomerGroups (GroupId, GroupName)

2) 客户组 (GroupId, GroupName)

3) CustomerInGroups (CustomerId, GroupId)

3) CustomerInGroups (CustomerId, GroupId)

using (var context = DataObjectFactory.CreateContext())
{                
    context.Customers.Add(entity);
    context.SaveChanges();
    return entity.Id;
}

How do I add a record into CustomerInGroups? EntityFramework doesn't generate entities for such many-to-many mapping tables

如何将记录添加到 CustomerInGroups 中?EntityFramework 不会为这种多对多映射表生成实体

Edit:

编辑:

Both the Id columns in Customer and CustomerGroups are set to auto increment.

Customer 和 CustomerGroups 中的 Id 列都设置为自动递增。

So in my CustomersGroup table, I have

所以在我的客户组表中,我有

Id          Name
----------------------------
1           Normal
2           VIP

I tried doing this as one of the posters suggested:

我尝试按照其中一张海报的建议进行操作:

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

However, when I did this, instead of creating a record in the mapping table like this:

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

CustomerId          GroupId
----------------------------
1                   2

What I got was

我得到的是

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

CustomerGroups
    Id          Name
    ----------------------------
    1           Normal
    2           VIP
    3           NULL

It actually created another entry in my CustomerGroups table, which is not what I want

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

采纳答案by Steven V

Flying a little blind since you didn't include what properties entityhas. 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.

因为你没有包括什么属性,所以有点盲目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;
}

If the relationship is setup correctly, EF will automatically insert a record into CustomerGroupsand insert a relationship into the CustomerInGroupstable.

如果关系设置正确,EF 会自动CustomerGroupsCustomerInGroups表中插入记录和插入关系。

EDIT:

编辑:

If you're trying to add an existing CustomerGroupto a new Customer. You'll want to get the CustomerGroupfrom the database first, then add it to the Customer entity you're inserting.

如果您尝试将现有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;
}

回答by Daniel

If you are trying to assing an existingcustomer to an _existing group and assuming that the CustomerGroup object exposes an ICollection do the following:

如果您尝试将现有客户分配给 _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
}

The Find() method is Entity Framework Code First (DbContext) way of finding by Id. I can't remember of the top of my head the "proper" ObjectContext way of doing it but but .Single(g => g.Id == 2) would also work.

Find() 方法是通过 Id 查找的实体框架代码优先 (DbContext) 方法。我不记得我的头顶是“正确的” ObjectContext 这样做的方式,但是 .Single(g => g.Id == 2) 也可以。

Ideally you'd give us a better idea of how your entities are mapped so we know how you are relating your entities.

理想情况下,您应该让我们更好地了解您的实体是如何映射的,以便我们知道您如何关联您的实体。

回答by mesut

In Addition to @Steven-v's answer, If you previously fetched customer groups and you don't want to fetch them again from db, you also can just attach them to the context.

除了@Steven-v 的回答之外,如果您之前提取过客户组并且不想再次从数据库中提取它们,您也可以将它们附加到上下文中。

foreach (var c in customer.CustomerGroups)
{
     _db.CustomerGroups.Attach(c);
}        
_db.Customer.Add(customer);
_db.SaveChanges();