3
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. 然而,Entity Framework 正在尝试在 SQL 端执行投影,其中没有与 Roles.GetRolesForUser 等效的位置。

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

4

3 回答 3

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,然后从其他来源(在您的情况下为角色提供者)扩充数据。

于 2013-08-06T18:32:05.947 回答
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()
    };
于 2013-08-06T18:34:40.057 回答
-1

您可以将 Queryable 转换为在本地执行的 Enumerable:

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()
于 2013-08-06T18:40:28.337 回答