EntityFramework将新对象添加到嵌套对象集合 [英] EntityFramework adding new object to nested object collection

查看:151
本文介绍了EntityFramework将新对象添加到嵌套对象集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题是以下的延续:

This question is a continuation of:

EntityFramework添加新对象一个集合

现在我明白当使用 DbSet EF将不会将整个集合加载到记忆

Now I understand that when using DbSet EF won't load the entire collection into memory

但是,如果我有如下代码:

But what if I have something like the following code:

public class User
{
    public int UserID { get; set; }
    public string UserName { get; set; }
    public ICollection<Role> Roles { get; set; }
}

public class Role
{
    public int RoleID { get; set; }
    public string RoleName { get; set; }
    public User User { get; set; }
}

public class MyContext : DbContext
{
    public DbSet<User> Users { get; set; }
    public DbSet<Role> Roles { get; set; }
}

public class SomeClass
{
    public void AssignRoleToUser(int userID, Role role)
    {
        var ctx = new MyContext();
        var user = ctx.Users.First(x => x.UserID.Equals(userID));

        user.Roles.Add(role);

        ctx.SaveChanges();
    }
}

在这种情况下,我没有使用 DbSet 对象将新对象添加到角色集合中,而是使用<$ c $向特定用户添加新角色c> ICollection 收集

In this case, I'm not using the DbSet object to add a new object to the Role collection, instead, I'm adding a new role to a specific user using an ICollection collection

在这种情况下会发生什么?

So what happens in this case?

EntityFramewrk必须将所有用户的角色加载到内存中以执行插入?

Does EntityFramewrk have to load into memory all the user's roles in order to perform the insert?

推荐答案

在提供上面的代码中,您不是添加新的作为您的ctx.user用户仅用于检索数据。这个SE帖子中有一些相似的问题 - Linq To Entities - 如何过滤子实体

In provide code above you are not adding new role as your ctx.Users is just used to retrieve data. Somewhat similar issue is addressed in this SE post - Linq To Entities - how to filter on child entities.

我会建议看看这篇简短有用的文章 - 实体框架4.0常见问题 - 入门指南

I would advice to look at this short and useful article - Entity Framework 4.0 FAQ – Getting Started Guide.

这篇关于EntityFramework将新对象添加到嵌套对象集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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