Tev*_*vis 2 c# asp.net-mvc entity-framework eager-loading dbcontext
DbContext使用预先加载查询 a时,需要Include("Navigation")填充导航属性。然而,在某些情况下,我想简单地为一个实体提供Include 所有导航属性。有没有办法做到这一点,或者有办法做到这一点?我假设你可以通过反思,但我宁愿避免这种情况。
我知道的:
var entity = db.Table.Include("Navigation1").Include("Navigation2").First();
Run Code Online (Sandbox Code Playgroud)
我想要的是:
var entity = db.Table.IncludeAll().First();
Run Code Online (Sandbox Code Playgroud)
不,那里没有。Entity Framework有意让您明确表示想要立即加载的内容,因为添加连接会使您的查询更繁重和更慢。这是为了保护您免受自己的伤害。如果您需要连接,那很好,但至少当您明确指定它们时,您会确切地知道发生了多少以及为什么会发生。
无论实体框架的设计者怎么想,我发现有一个合法的用例可以递归地、急切地加载所有数据库项:创建可以通过自动化测试轻松恢复的数据库内容快照。如果这就是您所追求的,您可能会发现这篇文章以及这个扩展方法非常有趣:
public static class EfExtensions
{
public static IQueryable<TEntity> IncludeAllRecursively<TEntity>(this IQueryable<TEntity> queryable,
int maxDepth = int.MaxValue, bool addSeenTypesToIgnoreList = true, HashSet<Type>? ignoreTypes = null)
where TEntity : class
{
var type = typeof(TEntity);
var includes = new List<string>();
ignoreTypes ??= new HashSet<Type>();
GetIncludeTypes(ref includes, prefix: string.Empty, type, ref ignoreTypes, addSeenTypesToIgnoreList, maxDepth);
foreach (var include in includes)
{
queryable = queryable.Include(include);
}
return queryable;
}
private static void GetIncludeTypes(ref List<string> includes, string prefix, Type type, ref HashSet<Type> ignoreSubTypes,
bool addSeenTypesToIgnoreList = true, int maxDepth = int.MaxValue)
{
var properties = type.GetProperties();
foreach (var property in properties)
{
var getter = property.GetGetMethod();
if (getter != null)
{
var isVirtual = getter.IsVirtual;
if (isVirtual)
{
var propPath = (prefix + "." + property.Name).TrimStart('.');
if (maxDepth <= propPath.Count(c => c == '.')) { break; }
includes.Add(propPath);
var subType = property.PropertyType;
if (ignoreSubTypes.Contains(subType))
{
continue;
}
else if (addSeenTypesToIgnoreList)
{
// add each type that we have processed to ignore list to prevent recursions
ignoreSubTypes.Add(type);
}
var isEnumerableType = subType.GetInterface(nameof(IEnumerable)) != null;
var genericArgs = subType.GetGenericArguments();
if (isEnumerableType && genericArgs.Length == 1)
{
// sub property is collection, use collection type and drill down
var subTypeCollection = genericArgs[0];
if (subTypeCollection != null)
{
GetIncludeTypes(ref includes, propPath, subTypeCollection, ref ignoreSubTypes, addSeenTypesToIgnoreList, maxDepth);
}
}
else
{
// sub property is no collection, drill down directly
GetIncludeTypes(ref includes, propPath, subType, ref ignoreSubTypes, addSeenTypesToIgnoreList, maxDepth);
}
}
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
注意:在遍历数据库项目时避免循环至关重要。默认情况下,它是使用忽略列表完成的ignoreSubTypes:添加每个看到的类型。这可能并不总是有效(例如,当项目“信件”包含类型为“发件人”和“收件人”时Person)。在这种情况下,您可以尝试使用maxDepth. 祝你好运,但不要开枪自杀!
| 归档时间: |
|
| 查看次数: |
3451 次 |
| 最近记录: |