gpt4 book ai didi

c# - 调用 DBSet.Find(id) 时,如何使 EF Code First 加载 "ICollection"属性

转载 作者:行者123 更新时间:2023-12-02 05:30:20 24 4
gpt4 key购买 nike

当我搜索像这样的“列表”时 DbSet<T>.Where(predicate)我可以加.Include("xxx")但这不适用于单个对象。

我不知道如何让 EF 加载 virtual Icollection<T>属性,调用时 DbSet<T>.Find(id)

最佳答案

使用当前的 API,您无法使用 Find 进行预加载方法:

来自 P erformance Considerations for Entity Framework 5

What you have to consider when using the Find method is:

...

Also, keep in mind that Find only returns the entity you are looking for and it does not automatically loads its associated entities if they are not already in the object cache. If you need to retrieve associated entities, you can use a query by key with eager loading.

所以最接近的是您可以获得的查询,例如使用 SingleOrDefault

dbSet.Include("xxx").SingleOrDefault(i => i.Id == id)

或者你可以显式地load the related entities找到之后:

using (var context = new Db())
{
var entity = context.SomeSet.Find(id);

context.Entry(entity).Collection(p => p.SomeCollection).Load();
}

关于c# - 调用 DBSet<T>.Find(id) 时,如何使 EF Code First 加载 "ICollection"属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12489878/

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