实体框架:多对多关系的ID列表 [英] Entity Framework: List of Ids for many to many relation

查看:79
本文介绍了实体框架:多对多关系的ID列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一种方法,它获取要分配给多对多关系的实体ID列表。

I have a method which is getting a List of Entity-IDs to be assigned to a many to many relation.

在这种情况下,最好的做法是在EntityA和EntityB之间添加关系?我应该加载列表B的每个元素并将其添加到A还是可以在不加载实体的情况下附加它?

What is the best practise in this case to add the relation between EntityA and EntityB? Do I load each element of list B and add it to A or can I attach it without loading the entites?

public void AddToNewA(string name, List<int> listOfBIds)
{
   var a = new EntityA();
   a.Name = name;

   ...
}
public class EntityA{
    public int ID {get; set;}
    public string Name {get; set;}
    public List<EntityB> EntityBList {get; set;}
}

publc class EntityB{
   public int ID {get; set;}
}

此外,如果我要使用存储库,会采用什么方法?

Furthermore what would be the approach if I would use a repository?

谢谢!

推荐答案

有可能甚至建议在 EntityA EntityB 之间建立连接,而无需从数据库中加载后者。为此,您可以为 EntityB 创建 stub实体,并将其作为 Unchanged 附加到上下文中:

It's possible and even recommended to establish the connections between EntityA and EntityB without loading the latter from the database. You do this by creating stub entities for EntityB and attaching them as Unchanged to the context:

public void AddToNewA(string name, List<int> listOfBIds)
{
    var a = new EntityA();
    a.Name = name;
    foreach(int id in listOfBIds)
    {
        var b = new EntityB { ID = id };
        context.Entry(b).State = System.Data.Entity.EntityState.Unchanged;
        a.EntityBs.Add(b);
    }
    context.EntityAs.Add(a);
    context.SaveChanges();
}

这篇关于实体框架:多对多关系的ID列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆