Der*_*ğlu 1 c# entity-framework entity-framework-core .net-core
我有包含的存储库类。以下代码适用于一对一关系。但是对于收藏我需要更改DbContext.Entry(model.Result).Reference(include).Load();
为DbContext.Entry(model.Result).Collection(include).Load();
public virtual async Task<TEntity> GetByIdAsync(object[] keyValues,
List<Expression<Func<TEntity, object>>> includes,
CancellationToken cancellationToken = default(CancellationToken))
{
var model = DbSet.FindAsync(keyValues, cancellationToken);
if (includes == null) return await model;
foreach (var include in includes)
//if (include.Body.Type.IsAssignableFrom(typeof(ICollection<>)))
DbContext.Entry(model.Result).Reference(include).Load();
return await model;
//return await DbSet.FindAsync(keyValues, cancellationToken);
}
Run Code Online (Sandbox Code Playgroud)
为了将引用和集合彼此分开,我在这里可以使用哪种条件?
谢谢。
编辑:示例对象是
System.Collections.Generic.IList`1 [[WestCore.Domain.Entities.WestLife.MhpProduct]]
通常,集合可以是ICollection或IList。
您可以使用更通用的方法来代替单独的Reference
/ Collection
方法Navigation
。不幸的是,它没有lambda表达式重载,因此您需要手动提取属性名称。由于您的方法设计不支持嵌套属性,因此可以从lambda表达式主体获取该信息,并将其转换为MemberExpression
:
foreach (var include in includes)
{
var propertyName = ((MemberExpression)include.Body).Member.Name;
DbContext.Entry(model.Result).Navigation(propertyName).Load();
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
1744 次 |
最近记录: |