我有几个Entity Framework 7(核心)实体:
> filestring
[1] "// Two-Dimensional Dynamic Array#include <iostream>using namespace std;typedef int* IntArrayPtr;int main(){ int d1, d2; cout << \"Enter the row and col dims of the array:"
我有一个字符串数组如下:
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" }
在EF6中,我可以做类似的事情:
context.Persons
.Include(x => x.Hobbies)
.Include(x => x.Address).ThenInclude(x => x.Country);
但在EF7 Include中不允许使用字符串。我创建了字典:
context.Persons.Include(entities[0]).Include(entities[1]);
会有类似的内容:
private readonly Dictionary<String, LambdaExpression> _properties = new Dictionary<String, LambdaExpression>();
我有扩展名:
x => x.Hobbies is for "Hobbies"
x => x.Address.Country is for "Address.Country"
我需要给予词典应用以下内容:
对于&#34; x =&gt; x.Hobbies&#34;只是做:
public static IQueryable<T> Include<T>(this IQueryable<T> source, Dictionary<String, LambdaExpression> properties) {
}
如果表达式类似于&#34; x =&gt; x.Address.Country&#34;添加:
source.Include(x => x.Hobbies);
可以这样做吗?
答案 0 :(得分:0)
不确定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)