2016-07-04 84 views
1

我有幾個實體框架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) { 
} 

,我需要給出的解釋適用於以下內容:

  1. Fo R 「X => x.Hobbies」 只是做:

    source.Include(x => x.Hobbies); 
    
  2. 如果表達式是像 「X => x.Address.Country」 補充:

    source.Include(x => x.Address).ThenInclude(x => x.Country); 
    

可以這樣做完了?

回答

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) 
+2

在EF7子實體必須包括使用ThenInclude ...這是我的問題之一... –

+0

我做了一個編輯我的答案,再次不確定EF 7,因爲我還沒有使用它,但也許這會幫助你。 –