使用LINQ将MembershipUser.Username拉入新对象

时间:2011-02-02 12:33:38

标签: linq

我有以下代码,我需要从成员资格表中提取每个用户的用户名:

var results = (from u in db.U_USER
               where u.Forename.ToLower().Contains(search)
               || u.Surname.ToLower().Contains(search)
               select new ExUser
               {
                   MembershipId = u.MembershipId,
                   Surname = u.Surname,
                   Forename = u.Forename,
                   Username = Membership.GetUser(u.MembershipId).UserName
               });

现在我知道为什么我得到了以下内容,但是有人可以推荐一个解决方案吗?

  

LINQ to Entities无法识别方法'System.Web.Security.MembershipUser GetUser

2 个答案:

答案 0 :(得分:2)

LINQ to Entities 尝试将您的选择表达式转换为T-SQL,但它不能,因为T-SQL中没有ExUser等。

通过调用AsEnumerable或类似内容来关闭表达式,然后执行投影:

var results = (from u in db.U_USER
               where u.Forename.ToLower().Contains(search)
               || u.Surname.ToLower().Contains(search)
               select u)
              .AsEnumerable()
              .Select(u => new ExUser
              {
                  MembershipId = u.MembershipId,
                  Surname = u.Surname,
                  Forename = u.Forename,
                  Username = Membership.GetUser(u.MembershipId).UserName
              });

答案 1 :(得分:1)

您可以使用AsEnumerable将结果强制转换为内存。当结果在内存中时,您可以在没有linq尝试将其转换为sql:

的情况下调用Membership.GetUser
var results = (from u in db.U_USER                        
                where u.Forename.ToLower().Contains(search) || u.Surname.ToLower().Contains(search)
               ).AsEnumerable().Select(u => new ExUser {
                MembershipId = u.MembershipId,                             
                Surname = u.Surname,                             
                Forename = u.Forename,                             
                Username = Membership.GetUser(u.MembershipId).UserName                        
                });