14

有没有其他选择:

Organizations.Include("Assets").Where(o => o.Id == id).Single()

我想看到类似的东西:

Organizations.Include(o => o.Assets).Where(o => o.Id == id).Single()

避免硬编码字符串“资产”。

4

7 回答 7

12

在 EF 4.1 中,有一个内置的扩展方法

您必须在项目中引用“EntityFramework”程序集(EF 4.1 所在的位置)并使用 System.Data.Entity。

using System.Data.Entity; 

如果你想包含嵌套实体,你可以这样做:

        db.Customers.Include(c => c.Orders.Select(o => o.LineItems))

不确定这是否适用于 EF4.0 实体(基于 ObjectContext)。

于 2011-09-10T00:04:30.087 回答
10

对于 Entity Framework 1.0,我为此创建了一些扩展方法。

public static class EntityFrameworkIncludeExtension
{
    public static ObjectQuery<T> Include<T>(this ObjectQuery<T> src, Expression<Func<T, StructuralObject>> fetch)
    {
        return src.Include(CreateFetchingStrategyDescription(fetch));
    }

    public static ObjectQuery<T> Include<T>(this ObjectQuery<T> src, Expression<Func<T, RelatedEnd>> fetch)
    {
        return src.Include(CreateFetchingStrategyDescription(fetch));
    }

    public static ObjectQuery<T> Include<T, TFectchedCollection>(this ObjectQuery<T> src, Expression<Func<T, IEnumerable<TFectchedCollection>>> fetch)
    {
        return src.Include(CreateFetchingStrategyDescription(fetch));
    }

    public static ObjectQuery<T> Include<T, FetchedChild>(this ObjectQuery<T> src, Expression<Func<T, RelatedEnd>> fetch, Expression<Func<FetchedChild, Object>> secondFetch)
        where FetchedChild : StructuralObject
    {
        return src.Include(CombineFetchingStrategies(fetch, secondFetch));
    }

    public static ObjectQuery<T> Include<T, FetchedChild>(this ObjectQuery<T> src, Expression<Func<T, RelatedEnd>> fetch, Expression<Func<FetchedChild, RelatedEnd>> secondFetch)
        where FetchedChild : StructuralObject
    {
        return src.Include(CombineFetchingStrategies(fetch, secondFetch));
    }

    public static ObjectQuery<T> Include<T, FetchedChild>(this ObjectQuery<T> src, Expression<Func<T, RelatedEnd>> fetch, Expression<Func<FetchedChild, StructuralObject>> secondFetch)
        where FetchedChild : StructuralObject
    {
        return src.Include(CombineFetchingStrategies(fetch, secondFetch));
    }

    public static ObjectQuery<T> Include<T, FetchedChild>(this ObjectQuery<T> src, Expression<Func<T, IEnumerable<FetchedChild>>> fetch, Expression<Func<FetchedChild, Object>> secondFetch)
        where FetchedChild : StructuralObject
    {
        return src.Include(CombineFetchingStrategies(fetch, secondFetch));
    }

    public static ObjectQuery<T> Include<T, FetchedChild>(this ObjectQuery<T> src, Expression<Func<T, IEnumerable<FetchedChild>>> fetch, Expression<Func<FetchedChild, RelatedEnd>> secondFetch)
        where FetchedChild : StructuralObject
    {
        return src.Include(CombineFetchingStrategies(fetch, secondFetch));
    }

    public static ObjectQuery<T> Include<T, FetchedChild>(this ObjectQuery<T> src, Expression<Func<T, IEnumerable<FetchedChild>>> fetch, Expression<Func<FetchedChild, StructuralObject>> secondFetch)
        where FetchedChild : StructuralObject
    {
        return src.Include(CombineFetchingStrategies(fetch, secondFetch));
    }

    private static String CreateFetchingStrategyDescription<TFetchEntity, TFetchResult>(
        Expression<Func<TFetchEntity, TFetchResult>> fetch)
    {
        fetch = (Expression<Func<TFetchEntity, TFetchResult>>)FixedWrappedMemberAcces.ForExpression(fetch);
        if (fetch.Parameters.Count > 1)
            throw new ArgumentException("CreateFetchingStrategyDescription support only " +
                "one parameter in a dynamic expression!");

        int dot = fetch.Body.ToString().IndexOf(".") + 1;
        return fetch.Body.ToString().Remove(0, dot);
    }

    private static String CreateFetchingStrategyDescription<T>(Expression<Func<T, Object>> fetch)
    {
        return CreateFetchingStrategyDescription<T, Object>(fetch);
    }

    private static String CombineFetchingStrategies<T, TFetchedEntity>(
                Expression<Func<T, Object>> fetch, Expression<Func<TFetchedEntity, Object>> secondFetch)
    {
        return CombineFetchingStrategies<T, Object, TFetchedEntity, Object>(fetch, secondFetch);
    }

    private static String CombineFetchingStrategies<TFetchEntity, TFetchResult, TFetchedEntity, TSecondFetchResult>(
        Expression<Func<TFetchEntity, TFetchResult>> fetch, Expression<Func<TFetchedEntity, TSecondFetchResult>> secondFetch)
    {
        return CreateFetchingStrategyDescription<TFetchEntity, TFetchResult>(fetch) + "." +
            CreateFetchingStrategyDescription<TFetchedEntity, TSecondFetchResult>(secondFetch);
    }
}

用法:

 Orders.Include(o => o.Product); // generates .Include("Product")
 Orders.Include(o => o.Product.Category); // generates .Include("Product.Category")
 Orders.Include(o => o.History); // a 1-* reference => .Include("History")
 // fetch all the orders, and in the orders collection.
 // also include the user reference so: .Include("History.User")
 // but because history is an collection you cant write o => o.History.User, 
 // there is an overload which accepts a second parameter to describe the fetching 
 // inside the collection.
 Orders.Include(o => o.History, h => h.User); 

我尚未在 EF4.0 上对此进行测试,但我希望它能够工作。

于 2010-04-06T16:19:20.077 回答
8

这很容易做到,使用 Expressions :

public static class ObjectQueryExtensions
{
    public static ObjectQuery<T> Include<T, TProperty>(this ObjectQuery<T> objectQuery, Expression<Func<T, TProperty>> selector)
    {
        MemberExpression memberExpr = selector.Body as MemberExpression;
        if (memberExpr != null)
        {
            return objectQuery.Include(memberExpr.Member.Name);
        }
        throw new ArgumentException("The expression must be a MemberExpression", "selector");
    }
}

您可以完全按照问题中的示例使用它


更新

改进版本,支持多个链式属性:

public static class ObjectQueryExtensions
{
    public static ObjectQuery<T> Include<T, TProperty>(this ObjectQuery<T> objectQuery, Expression<Func<T, TProperty>> selector)
    {
        string propertyPath = GetPropertyPath(selector);
        return objectQuery.Include(propertyPath);
    }

    public static string GetPropertyPath<T, TProperty>(Expression<Func<T, TProperty>> selector)
    {
        StringBuilder sb = new StringBuilder();
        MemberExpression memberExpr = selector.Body as MemberExpression;
        while (memberExpr != null)
        {
            string name = memberExpr.Member.Name;
            if (sb.Length > 0)
                name = name + ".";
            sb.Insert(0, name);
            if (memberExpr.Expression is ParameterExpression)
                return sb.ToString();
            memberExpr = memberExpr.Expression as MemberExpression;
        }
        throw new ArgumentException("The expression must be a MemberExpression", "selector");
    }
}

例子 :

var query = X.Include(x => x.Foo.Bar.Baz) // equivalent to X.Include("Foo.Bar.Baz")
于 2010-04-06T16:27:28.120 回答
2

请参阅“告别硬编码的 ObjectQuery(T).Include 调用”。

于 2010-08-08T17:31:07.070 回答
2

另一种解决方案是使用 EntitySet.Name 检索实体名称。
您的代码将是:

var context = new DBContext();  
context.Organizations.Include(context.Assets.EntitySet.Name).Where(o => o.Id == id).Single()
于 2012-04-14T07:36:20.830 回答
1

好消息是 EF4 CTP4 目前支持此功能。

于 2010-09-20T08:53:51.363 回答
1

另一种选择是使用 TT 模板在您的类中包含一个内部部分类。

T4代码:

<#
    region.Begin("Member Constants");
#>
   public partial class <#=code.Escape(entity)#>Members
   {
<#
    foreach (EdmProperty edmProperty in entity.Properties.Where(p => p.TypeUsage.EdmType is PrimitiveType && p.DeclaringType == entity))
    {
        bool isForeignKey = entity.NavigationProperties.Any(np=>np.GetDependentProperties().Contains(edmProperty));
        bool isDefaultValueDefinedInModel = (edmProperty.DefaultValue != null);
        bool generateAutomaticProperty = false;
        #>
        public const string <#=code.Escape(edmProperty)#> = "<#=code.Escape(edmProperty)#>";
        <#
    }
    #>
    }
    <#
    region.End();
#>

这将产生类似的东西:

    #region Member Constants
   public partial class ContactMembers
   {
        public const string ID = "ID";
                public const string OriginalSourceID = "OriginalSourceID";
                public const string EnabledInd = "EnabledInd";
                public const string EffectiveDTM = "EffectiveDTM";
                public const string EndDTM = "EndDTM";
                public const string EnterDTM = "EnterDTM";
                public const string EnterUserID = "EnterUserID";
                public const string LastChgDTM = "LastChgDTM";
                public const string LastChgUserID = "LastChgUserID";
            }

    #endregion
于 2011-05-09T15:12:57.650 回答