如何在LINQ to Entities中执行一个方法

时间:2013-08-06 18:29:33

标签: linq linq-to-entities entity-framework-5

var users = from u in db.UserProfiles select new UsersViewModel{ 
                            UserName = u.UserName,
                            UserId = u.UserId,
                            IsDisabled = u.IsDisabled,
                            Role = Roles.GetRolesForUser(u.UserName).FirstOrDefault()
                        };

我想从数据库中选择角色并创建UsersViewModel列表。但是实体框架试图在SQL端执行投影,其中没有与Roles.GetRolesForUser等效的东西。

什么是替代它或我如何在查询中执行任何方法?

3 个答案:

答案 0 :(得分:2)

最简单的方法是从SQL获取所需的数据,然后在查询执行后,遍历结果并从代码中的函数中填充其他详细信息。

示例:

var users = (from u in db.UserProfiles select new UsersViewModel{ 
                            UserName = u.UserName,
                            UserId = u.UserId,
                            IsDisabled = u.IsDisabled
                        }).ToList();
foreach(var user in users){
    user.Role = Roles.GetRolesForUser(u.UserName).FirstOrDefault();
}

这里要记住的关键是要分离你正在做的事情(理解你的架构中关注点的分离)。首先处理SQL,然后从其他来源扩充数据,在您的情况下是角色提供程序。

答案 1 :(得分:1)

您可以在创建ViewModels之前强制执行查询,方法是添加ToList()

var users = from u in db.UserProfiles.ToList() 
    select new UsersViewModel{ 
        UserName = u.UserName,
        UserId = u.UserId,
        IsDisabled = u.IsDisabled,
        Role = Roles.GetRolesForUser(u.UserName).FirstOrDefault()
    };

正如CodeMonkey1313所说,我强烈建议您在查询中应用某种过滤器:

var users = from u in db.UserProfiles
    .Where( x => /* apply filter here */ )
    .ToList() //Force query to execute
    select new UsersViewModel { 
        UserName = u.UserName,
        UserId = u.UserId,
        IsDisabled = u.IsDisabled,
        Role = Roles.GetRolesForUser(u.UserName).FirstOrDefault()
    };

答案 2 :(得分:-1)

您可以将Iqueryable转换为在本地执行的Ienumerable:

var users = (from u in db.UserProfiles select new UsersViewModel{ 
                        UserName = u.UserName,
                        UserId = u.UserId,
                        IsDisabled = u.IsDisabled)}
                     ).AsEnumerable()
                      .Select(u => new { 
                        UserName = u.UserName,
                        UserId = u.UserId,
                        IsDisabled = u.IsDisabled,
                        Role = Roles.GetRolesForUser(u.UserName) })
                      .FirstOrDefault()