重用LINQ选择功能

时间:2014-12-30 23:03:47

标签: c# linq entity-framework

我有以下代码:

internal static IQueryable<UserModel> SelectUser(this IQueryable<User> query, bool getChildren) {
    log.DebugFormat("create the select statement for an individual user {0}", getChildren ? "with children" : "without children");
    var res = query.Select(u => new UserModel {
        // [...] unimportant stuff
        Groups = u.Groups.Select(g => new GroupModel {
            Name = g.Name,
            Description = g.Description,
            ID = g.ID
        }).Take(10),
        CreatedGroups = !getChildren ? null : u.CreatedGroups.Select(g => new GroupModel {
            Name = g.Name,
            Description = g.Description,
            ID = g.ID
        }).Take(10)
        // [...] more stuff like above just different types
    });
    return res;
}

此代码完美无缺。但我有点恼火,我用这个代码违反了DRY原则。最重要的是,有更多情况,我需要将Group映射到GroupModel

所以我决定创建一个扩展方法:

public static IEnumerable<GroupModel> SelectChildGroups(this ICollection<Group> query) {
    return query.Select(g => new GroupModel {
        Name = g.Name,
        ID = g.ID
    });
}

这给了我以下例外:

'LINQ to Entities' erkennt die Methode 'System.Collections.Generic.IEnumerable`1[Coding.Lizards.Gekkota.Web.Models.GroupModel] SelectChildGroups(System.Collections.Generic.ICollection`1[Coding.Lizards.Gekkota.Web.Models.Group])' nicht, und diese Methode kann nicht in einen Speicherausdruck übersetzt werden. 

英文:

'LINQ to Entities' does not recognize the method 'System.Collections.Generic.IEnumerable`1[Coding.Lizards.Gekkota.Web.Models.GroupModel] SelectChildGroups(System.Collections.Generic.ICollection`1[Coding.Lizards.Gekkota.Web.Models.Group])', and this method cannot be translated into a store expression. 

我能够将错误追溯到我发布的功能。有人知道如何解决它吗?

修改

属性GroupsCreatedGroups属于ICollection<Group>类型。该代码与Linq-To-Entities一起使用。

1 个答案:

答案 0 :(得分:4)

尝试将Func存储在变量中,然后重复使用它。像这样:

internal static IQueryable<UserModel> SelectUser(this IQueryable<User> query, bool getChildren) {
    log.DebugFormat("create the select statement for an individual user {0}", getChildren ? "with children" : "without children");

    var res = query.Select(u => new UserModel {
        // [...] unimportant stuff
        Groups = u.Groups.AsQueryable().Select(MyLinqExpressions.fSelect).Take(10),
        CreatedGroups = !getChildren ? null : u.CreatedGroups.AsQueryable().Select(MyLinqExpressions.fSelect).Take(10)
        // [...] more stuff like above just different types
    });
    return res;
}

然后是另一个班级:

public static class MyLinqExpressions {
    public static Func<Group,GroupModel>
        fSelect = g => new GroupModel {
            Name = g.Name,
            Description = g.Description,
            ID = g.ID
        };
}