实体框架包含()强类型

问题描述:

有没有办法使用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://*.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://*.com/questions/5376421/ef-including-other-entities-generic-repository-pattern/5376637#5376637 – 2011-05-23 21:24:17

这是已经可以在实体框架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

幸得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