C# 实体框架Include()强类型
是否有方法使用System.Data.Entity.Include方法使其强类型化?在下面的方法中,升级是一个ICollectionC# 实体框架Include()强类型,c#,asp.net,entity-framework,C#,Asp.net,Entity Framework,是否有方法使用System.Data.Entity.Include方法使其强类型化?在下面的方法中,升级是一个ICollection public IEnumerable GetAllTypes(){ Database.Configuration.LazyLoadingEnabled=false; return Database.EscalationTypes .包括(“升级”) .包括(“升级.主要”) .包括(“升级.备份”) .包括(“Escalation.Primary.ContactI
public IEnumerable GetAllTypes(){
Database.Configuration.LazyLoadingEnabled=false;
return Database.EscalationTypes
.包括(“升级”)
.包括(“升级.主要”)
.包括(“升级.备份”)
.包括(“Escalation.Primary.ContactInformation”)
.Include(“Escalation.Backup.ContactInformation”).ToList();
}
学分归:
这已在实体框架4.1中提供 有关如何使用“包含”功能的参考,请参见此处,它还显示了如何包含多个级别:
强类型的
Include()
方法是一个扩展方法,因此您必须记住使用System.Data.Entity声明代码>语句。该逻辑已包含在System.Data.Entity命名空间中。可以将Include与表达式一起使用。请注意,上面的升级是一个ICollection。如果您有EFv4.1,则不必使用魔术字符串:这也会引起您的兴趣:这应该标记为正确答案。特别是对于我们这些习惯于使用
语句重新筛选的人来说,我们忘记了我们需要不时手动添加一个语句。缺少的using语句让我感到困惑。谢谢提醒。是否有理由不使用此扩展名(或者相反:是否有理由将include
与字符串一起使用)?
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();
}
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)