应用包括基于ThenInclude的Lambda表达式字典
问题描述:
我有几个实体框架7(核心)的实体:应用包括基于ThenInclude的Lambda表达式字典
public class Person {
public virtual Address Address { get; set; }
public virtual ICollection<Hobby> Hobbies { get; set; }
}
public class Address {
public String Street { get; set; }
public virtual Country Country { get; set; }
}
而且我有一个字符串数组如下:
String[] entities = new String[] { "Hobbies", "Address.Country" }
鉴于此字符串数组我:
context.Persons
.Include(x => x.Hobbies)
.Include(x => x.Address).ThenInclude(x => x.Country);
在EF6我可以这样做:
context.Persons.Include(entities[0]).Include(entities[1]);
但是在EF7 Include中不允许字符串。我创建了词典:
private readonly Dictionary<String, LambdaExpression> _properties = new Dictionary<String, LambdaExpression>();
这将是这样的:
x => x.Hobbies is for "Hobbies"
x => x.Address.Country is for "Address.Country"
和我有扩展名:
public static IQueryable<T> Include<T>(this IQueryable<T> source, Dictionary<String, LambdaExpression> properties) {
}
,我需要给出的解释适用于以下内容:
-
Fo R “X => x.Hobbies” 只是做:
source.Include(x => x.Hobbies);
-
如果表达式是像 “X => x.Address.Country” 补充:
source.Include(x => x.Address).ThenInclude(x => x.Country);
可以这样做完了?
答
不确定ThenInclude()
和EF 7,但你可以做你的存储库这样的事情(使用EF 6测试):
public MyEntity GetMyEntity_EagerlyLoad(DbContext context, int id, params Expression<Func<MyEntity, object>>[] propertiesToLoad)
{
var q = context.MyEntities.Where(m => m.ID == id);
foreach (var prop in propertiesToLoad)
q = q.Include(prop);
return q.SingleOrDefault();
}
然后你可以这样调用:
repo.GetMyEntity_EagerlyLoad(context, id, m => m.Property1, m => m.Property2, m => m.Property1.NestedProperty)
编辑:还有另一种方法来使用投影进行EF加载。你可以做一个通用的存储库方法是这样的:
public MyEntity GetMyEntity_EagerlyLoad<T>(DbContext context, int id, Expression<Func<MyEntity, T>> loadingProjection, Func<T, MyEntity> resultProjection)
{
var q = context.MyEntities.Where(m => m.ID == id);
return q.Select(loadingProjection).AsEnumerable().Select(resultProjection).SingleOrDefault();
}
然后用你想装的属性,并且希望该方法返回的实体称之为:
repo.GetMyEntity_EagerlyLoad(context, id, m => new { myEntity = m, m.Property1, m.Property2, m.Property1.NestedProperty }, m => m.myEntity)
在EF7子实体必须包括使用ThenInclude ...这是我的问题之一... –
我做了一个编辑我的答案,再次不确定EF 7,因为我还没有使用它,但也许这会帮助你。 –