gpt4 book ai didi

c# - EntityFramework 将新对象添加到嵌套对象集合

转载 作者:太空宇宙 更新时间:2023-11-03 11:11:30 25 4
gpt4 key购买 nike

这个问题是以下问题的延续:

EntityFramework adding new object to a collection

现在我明白了,当使用 DbSet 时,EF 不会将整个集合加载到内存中

但是如果我有类似下面的代码怎么办:

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 对象将新对象添加到 Role 集合,而是将新角色添加到使用 ICollection 集合的特定用户

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

EntityFramewrk 是否必须将所有用户角色加载到内存中才能执行插入?

最佳答案

在上面提供的代码中,您没有添加新角色,因为您的 ctx.Users 仅用于检索数据。这篇 SE 帖子 - Linq To Entities - how to filter on child entities 解决了一些类似的问题.

我建议您看看这篇简短而有用的文章 - Entity Framework 4.0 FAQ – Getting Started Guide .

关于c# - EntityFramework 将新对象添加到嵌套对象集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13868030/

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