如何在不将项目的父项和同级项加载到内存的情况下将项目添加到存储库 [英] How to add an item to the repository without loading the item's Parent and siblings into memory

查看:41
本文介绍了如何在不将项目的父项和同级项加载到内存的情况下将项目添加到存储库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

EntityFramework,代码优先解决方案.

EntityFramework, code first solution.

我的存储库"

public abstract class BaseEfDataRepository : DbContext
{
    public IDbSet<Account> Accounts { get; set; }
}

帐户

public virtual List<User> Users { get; private set; }

如何使用Linq-To-Entities将新的 User 添加到 Account ,而不加载整个 Account 对象,或者至少不从中加载整个 Users 集.

How can I add a new User to an Account, using Linq-To-Entities, without loading the entire Account object, or at least without loading the entire Users set from it.

我通常这样做是:

var account = context.Accounts.FirstOrDefault(acc => acc.Id == accountId);
account.Users.Add(newUser);
context.Save();

但是我注意到这会将整个集合加载到内存中,我想避免这种情况.

but I've noticed that this loads the entire set into memory, which I want to avoid.

有可能吗?我有什么选择?我可以想到:在 DbContext 中公开 Users ,然后从中添加用户.但这会对我造成其他所有类型的问题.

Is it possible? What are my options? I can think of: Expose the Users in DbContext and add the user from there. But this would cause all other kind of problems for me.

还有其他选择吗?

推荐答案

如果您知道 Account 的ID值,则可以创建 stub实体并添加 User 到其 Users 集合:

If you know the Account's id value, you can create a stub entity and add the User to its Users collection:

var acc = new Account { Id = accountId };
context.Accounts.Attach(acc);
acc.Users.Add(newUser);
context.SaveChanges();

由于 Account.Users 有一个私有的setter,所以我假设您在构造函数中初始化了集合.

Since Account.Users has a private setter, I assume you initialize the collection in the constructor.

这篇关于如何在不将项目的父项和同级项加载到内存的情况下将项目添加到存储库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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