实体框架包含()强类型
问题描述:
有没有办法使用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();
}
答
这是已经可以在实体框架4.1。
在这里看到了如何使用包括功能的引用,它也显示了如何将包含多个层次:http://msdn.microsoft.com/en-us/library/gg671236(VS.103).aspx
强类型Include()
方法是一个扩展方法,所以你一定要记得申报using System.Data.Entity;
声明。
答
幸得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命名空间中。您可以使用包含表达式
如果你有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
这也可能会让你感兴趣:http://*.com/questions/5376421/ef-including-other-entities-generic-repository-pattern/5376637#5376637 – 2011-05-23 21:24:17