我遇到的问题是,查询工作正常,除了查询部分的问题连接,连接查询在查询之外工作但是当我放入其中时它将无法工作并在在代码下结束。
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 to Entities无法识别方法'System.String Concat(System.String [])'方法,这个方法无法翻译 到商店表达式。“} System.SystemException {System.NotSupportedException}
答案 0 :(得分:0)
问题正是错误告诉你的 - String.Concat
无法转换为SQL查询。因此,将查询分为两部分 - 一部分用于查询数据库,另一部分用于在执行连接之前将数据带入内存。
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()),
};
答案 1 :(得分:-1)
为什么使用string.Contat
?做个总结。
tag = mainQuery.AccountName + (childQuery.ToArray().Aggregate(x,y)=> x + "," + y)
如果上述方法没有帮助,我建议您进行两次单独的查询。 首先是获取联系人,第二个是计算HashTags。然后合并它。它会提高性能。
我认为最好的方法是使用本机T-SQL和实体框架。
class MyDataRow
{
public int Id {get;set;}
public double FieldB {get;set;}
public string FieldC {get;set;}
}
string queryText = @"
SELECT
t1.Id,
t1.FieldB,
(SELECT hashTag FROM table_2 WHERE contactId = t1.Id) AS FieldC
FROM table_1 AS t1
";
// EF will map properties automatically and you do not have to write and configure stored procedure...
List<MyDataRow> rows = context.ExecuteStoreQuery<MyDataRow>(queryText).ToList();