LINQ请求与2个相关实体

时间:2012-03-14 12:37:27

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

我有以下代码:

        var result = from i in _dbContext.Users
                     orderby i.aspnet_User.aspnet_Membership.CreateDate
                     select new ITW2012Mobile.Models.BusinessLogic.PreReg()
                     {
                         UserID = i.ID,
                         Company = i.Company,
                         FirstName = i.FirstName,
                         LastName = i.LastName,
                         IsUsed = i.IsUsed,
                         Title = i.Title,
                         Email = ((i.IsUsed) ? i.aspnet_User.aspnet_Membership.Email : i.PreRegEmail.Email)
                     };
        var q = result.ToList();

所以,当flag isUsed == true时,我们需要从会员中获取电子邮件,否则从PreRegEmail获取。但是这段代码不起作用,得到“无法解决SELECT语句中第7列的排序规则冲突。”。为什么以及如何解决?

1 个答案:

答案 0 :(得分:1)

error消息实际上来自sql server。您不能将具有不同排序规则的两列合并为一列。我建议使用linq-to-entities将它们选择为单独的属性,而不是linq-to-objects来构建您的电子邮件属性,如此

var result = from i in _dbContext.Users
             orderby i.aspnet_User.aspnet_Membership.CreateDate
             select new 
             {
               UserID = i.ID,
               Company = i.Company,
               FirstName = i.FirstName,
               LastName = i.LastName,
               IsUsed = i.IsUsed,
               Title = i.Title,
               AspEmail = i.aspnet_User.aspnet_Membership.Email,
               PreRegEmail = i.PreRegEmail.Email,
             };   

var q = from i in result.AsEnumerable()
        select new ITW2012Mobile.Models.BusinessLogic.PreReg()
        {
          UserID = i.ID,
          Company = i.Company,
          FirstName = i.FirstName,
          LastName = i.LastName,
          IsUsed = i.IsUsed,
          Title = i.Title,
          Email = i.IsUsed ? i.AspEmail  : i.PreRegEmail,
        };

var final = q.ToList();