在返回多个项目的 LINQ 表达式中获取成员资格数据时出错
我正在尝试创建一个显示员工列表的页面。
所有员工身份验证数据都存储在 .NET 成员资格表中,名称等其他数据存储在名为“Employees”的相关表中。
这是我获取员工列表的代码:
var viewModel = employees.OrderBy(e => e.Name).
Select(e => new EmployeeViewModel
{
EmployeeId = e.EmployeeID,
Name = e.Name,
Email = Membership.GetUser(e.UserID).Email,
Active = e.Active
});
我收到此错误:
LINQ to Entities 无法识别“System.Web.Security.MembershipUser GetUser(System.Object)”方法,并且此方法无法转换为存储表达式。
我做了一些研究,发现我需要将 Membership.GetUser
函数拉到 LINQ 表达式之外。如果我只得到一名员工,那么这会非常有用,但我返回一个列表,因此每次迭代的用户都会不同。
有人知道我该如何解决这个问题吗?
I'm trying to create a page that displays a list of employees.
All the employee authentication data is stored in the .NET membership tables, with other data like Name stored in a related table named Employees.
Here's my code that is getting the list of employees:
var viewModel = employees.OrderBy(e => e.Name).
Select(e => new EmployeeViewModel
{
EmployeeId = e.EmployeeID,
Name = e.Name,
Email = Membership.GetUser(e.UserID).Email,
Active = e.Active
});
I get this error:
LINQ to Entities does not recognize the method 'System.Web.Security.MembershipUser GetUser(System.Object)' method, and this method cannot be translated into a store expression.
I did some research, and found that I need to pull the Membership.GetUser
function outside of the LINQ expression. This would work great if I was only getting a single employee, but I'm returning a list, so the user would be different on each iteration.
Anyone know how I can fix this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以通过在
Select(..)
之前插入ToArray()
来在“客户端”端评估您的选择:在这种情况下,EF 不要尝试翻译 <代码>Membership.GetUser 方法。
编辑:
正如评论中指出的,该解决方案虽然解决了您的问题,但引入了另一个问题:它将执行 N+1 选择,其中 N 是员工数量。
为了避免这种情况,您可以在 EF 模型中映射
MemberShip
表,并在MemberShip
和Employee
表之间创建关系。然后,您可以一键获取所有数据,而无需使用Membership.GetUser()
。You can evaluate your select on the "client" side with inserting a
ToArray()
before theSelect(..)
:In this case EF don't try to translate
Membership.GetUser
method.EDIT:
As pointed out in the comments, this solution although solves your problem, but introduces another one: it will execute N+1 selects where N is the count of employees.
To avoid that you can map your
MemberShip
tables in your EF model and you can create an relation between theMemberShip
and yourEmployee
table. Then you can get all the data with one select and without usingMembership.GetUser()
.