2011-05-23 102 views
47

有沒有辦法使用System.Data.Entity.Include方法來強制類型化?在下面的方法中,升級是ICollection <>。實體框架包含()強類型

public IEnumerable<EscalationType> GetAllTypes() { 
    Database.Configuration.LazyLoadingEnabled = false; 
    return Database.EscalationTypes 
    .Include("Escalation") 
    .Include("Escalation.Primary") 
    .Include("Escalation.Backup") 
    .Include("Escalation.Primary.ContactInformation") 
    .Include("Escalation.Backup.ContactInformation").ToList(); 
} 
+0

如果你有EFv4.1,你不必使用魔術字符串:http://stackoverflow.com/questions/5247324/ef-code-first-ctp5-using-include-method-with-many-to -many-table/5247423#5247423 – 2011-05-23 21:21:39

+0

這也可能會讓你感興趣:http://stackoverflow.com/questions/5376421/ef-including-other-entities-generic-repository-pattern/5376637#5376637 – 2011-05-23 21:24:17

回答

86

這是已經可以在實體框架4.1。

在這裏看到了如何使用包括功能的引用,它也顯示瞭如何將包含多個層次:http://msdn.microsoft.com/en-us/library/gg671236(VS.103).aspx

強類型Include()方法是一個擴展方法,所以你一定要記得申報using System.Data.Entity;聲明。

+4

這應該被標記爲正確的答案。特別是對於我們那些習慣於使用ReSharper建議使用'''語句的人,我們忘記了我們需要不時手動添加一個。 – gligoran 2015-03-20 10:58:53

+1

缺少使用聲明是讓我。感謝您的提醒。 – BrianLegg 2016-02-04 20:27:48

+0

應該有一個不使用這個擴展的理由(或者其他方式:是否有理由使用'include'和'string'參數)? – Michel 2016-08-26 13:39:06

6

幸得Joe Ferner

public static class ObjectQueryExtensionMethods { 
    public static ObjectQuery<T> Include<T>(this ObjectQuery<T> query, Expression<Func<T, object>> exp) { 
    Expression body = exp.Body; 
    MemberExpression memberExpression = (MemberExpression)exp.Body; 
    string path = GetIncludePath(memberExpression); 
    return query.Include(path); 
    } 

    private static string GetIncludePath(MemberExpression memberExpression) { 
    string path = ""; 
    if (memberExpression.Expression is MemberExpression) { 
     path = GetIncludePath((MemberExpression)memberExpression.Expression) + "."; 
    } 
    PropertyInfo propertyInfo = (PropertyInfo)memberExpression.Member; 
    return path + propertyInfo.Name; 
    } 
} 
ctx.Users.Include(u => u.Order.Item) 
+10

該邏輯已包含在內在System.Data.Entity命名空間中。您可以使用包含表達式>。請注意,升級是ICollection 。 – 2011-05-23 21:09:09