[c#]串联在 Linq 查询中的 Linq 查询的结果

标签: Linq .Net C#
发布时间: 2017/2/28 21:09:58
注意事项: 本文中文内容可能为机器翻译,如要查看英文原文请点击上面连接.

问题是,查询好作品除了部分的查询的执行并置问题,查询外,但当我把里面的串联查询作品将不工作和下代码就会得到错误。

var list = (from x in context.Contacts
where !x.DeleteFlag && !x.EmptyFlag
select new models.Contacts.list
{

// CONTACT
Contact = x,

// CONTACT'S PHONE
Phone =
   context.EContacts.Where(e => e.id == x.PrimaryPhoneid)
  .Select(e => e.Title).FirstOrDefault(),

// CONTACT'S EMAIL
Email =
   context.EContacts.Where(e => e.id == x.PrimaryEmailid)
   .Select(e => e.Title).FirstOrDefault(),

// CONTACT'S ACCOUNT
Account =
   context.Accounts.Where(e => e.id == x.Parentid)
   .Select(e => e.AccountName).FirstOrDefault(),

// Problem Is Here With This Query
tag =  string.Concat((from HE in context.HashTagEntities
   join t in context.Accounts on HE.ParentEntityid equals t.id
   where HE.ParentEntityId == 3 &&
   t.AccountName == context.Accounts.Where(e => e.id == x.Parentid).Select(e => e.AccountName)
   .FirstOrDefault()
   from tag in context.HashTags
   where HE.HashTagid == tag.id
   select tag.HashTagText).ToArray()),

}).OrderBy(o => o.Contact.FirstName);

错误︰

{"LINQ 到实体不能识别的方法 ' System.String Concat(System.String[])' 的方法,和这种方法不能转化为一个存储表达式。"} System.SystemException {System.NotSupportedException}

解决方法 1:

这个问题正是错误告诉你- String.Concat 不能转换为 SQL 查询。所以打破查询分为两部分 — — 一个查询数据库,第二,做 concat 之前将数据带进内存。

    var listQuery =
        from x in context.Contacts
        where !x.DeleteFlag && !x.EmptyFlag
        orderby x.FirstName
        select new
        {
            Contact = x,
            Phone =
                context.EContacts.Where(e => e.id == x.PrimaryPhoneid)
                .Select(e => e.Title).FirstOrDefault(),
            Email =
                context.EContacts.Where(e => e.id == x.PrimaryEmailid)
                .Select(e => e.Title).FirstOrDefault(),
            Account =
                context.Accounts.Where(e => e.id == x.Parentid)
                .Select(e => e.AccountName).FirstOrDefault(),
            tags =
                from HE in context.HashTagEntities
                join t in context.Accounts on HE.ParentEntityid equals t.id
                where HE.ParentEntityId == 3 &&
                    t.AccountName == context.Accounts.Where(e => e.id == x.Parentid).Select(e => e.AccountName)
                    .FirstOrDefault()
                from tag in context.HashTags
                where HE.HashTagid == tag.id
                select tag.HashTagText,                
        };

    var list =
        from x in listQuery.ToArray()
        select new models.Contacts.list()
        {
            Contact = x.Contact,
            Phone = x.Phone,
            Email = x.Email,
            Account = x.Account,
            tags = String.Concat(x.tags.ToArray()),
        };
官方微信
官方QQ群
31647020