Ado.net实体.include()方法不起作用

时间:2009-10-02 02:56:31

标签: entity-framework ado.net include

我有这个功能

public static AdoEntity.Inspector GetInspectorWithInclude(int id, List<string> properties)
    {
        using (var context = new Inspection09Entities())
        {
            var query = context.Inspector;
            if (properties != null)
            {
                foreach (var prop in properties)
                {
                    if (!string.IsNullOrEmpty(prop))
                        query.Include(prop);
                }
            }
            return query.Where(i => i.ID == id).First();
        }
    }

我用来从数据库中获取“检查员”,还有一个额外的功能来指定“包括”数据的内容。所以需要一个List&lt;'string'&gt;并将它们包含在查询中。此函数似乎不起作用,因为返回的对象仍然不包括请求的数据。有人能告诉我这种方法/方法有什么问题。

提前致谢。

解决方案

感谢 Misha N。建议,我已经设想了这个扩展ObjectQuery类的EF帮助器。希望其他人可能会发现它很有用。

/// <summary>
/// The include extesion that takes a list and returns a object query with the included data.
/// </summary>
/// <param name="objectQuery">
/// The object query.
/// </param>
/// <param name="includes">
/// The list of strings to include.
/// </param>
/// <typeparam name="T">
/// </typeparam>
/// <returns>
/// An object query of T type with the included data.
/// </returns>
public static ObjectQuery<T> Include<T>(this ObjectQuery<T> objectQuery, List<string> includes)
{
    ObjectQuery<T> query = objectQuery;
    if (includes != null) includes.ForEach(s => { if (!string.IsNullOrEmpty(s)) query = query.Include(s); });

    return query;
}

用法示例。

using(var context = new MyEntity())
{
    var includes = new List<string>
    {
        "Address",
        "Orders",
        "Invoices"
    }
    return context.CustomerSet.Include(includes).First(c => c.ID == customerID);
}

1 个答案:

答案 0 :(得分:3)

你的方法没有问题,只需要改变一件小事:

public static AdoEntity.Inspector GetInspectorWithInclude(int id, List<string> properties)
{
    using (var context = new Inspection09Entities())
    {
        var query = context.Inspector;
        if (properties != null)
        {
            foreach (var prop in properties)
            {
                if (!string.IsNullOrEmpty(prop))
                    query = query.Include(prop);// <--- HERE
            }
        }
        return query.Where(i => i.ID == id).First();
    }
}

ObjectQuery.Include()方法返回更改后的ObjectQuery对象,您还没有对初始查询进行更改。

希望这有帮助