我有 3 个EF实体:Appeal
,AppealPerson
,Person
。
Appeal
实体加入的 Person
和AppealPerson
个实体(多对多关系)。
我想选择带有连接人全名的申诉。
+----------+----------+--------------------------------------------------+
| AppealId | Appeal.* | Person.Surname + Person.Name + Person.MiddleName |
+----------+----------+--------------------------------------------------+
| 1 | ..info.. | Aaa Aaa Aaa, Bbb Bbb Bbb, Ccc Ccc Ccc |
+----------+----------+--------------------------------------------------+
| 2 | ..info.. | Aaa Aaa Aaa, Bbb Bbb Bbb |
+----------+----------+--------------------------------------------------+
现在我正在使用此查询:
context.Appeals
.Select(a => new
{
Appeal = a,
Persons = a.AppealPersons
.Select(ap => ap.Person)
.Select(p => new { p.Surname, p.Name, p.MiddleName })
.ToList()
})
.AsEnumerable()
.Select(a => new
{
Id = a.Appeal.Id,
Persons = a.Persons.Select(p => string.Format("{0} {1} {2}", p.Surname, p.Name, p.MiddleName).Trim()),
})
.ToList<object>();
此查询非常慢。列出在30秒内生成~500行。 请帮助优化查询。
答案 0 :(得分:0)
尝试连接,例如:
from a in context.Appeals
join ap in context.AppealPerson
on a.Id equals ap.AppealId
join p in context.Person
on p.Id equals ap.PersonId
...
答案 1 :(得分:0)
考虑一下你的人际关系,我认为你可以用GroupBy
条款做到这一点。鉴于格式化必须在客户端发生,如果你有一个函数包含了这个,或者更好的话,覆盖ToString
上的Person
public partial class Person
{
...
public string override ToString()
{
return String.Format("{0} {1} {2}", Surname, Name, MiddleName).Trim();
}
}
...
context.AppealPersons
.GroupBy(ap => ap.Appeal.Id, ap => ap,
(key, g) => new {
AppealId = key,
Appeal = g.FirstOrDefault().Appeal,
Persons = String.Join(",", g.Select(x => x.Person).AsEnumerable()
.Select(p => p.ToString()))
})
.ToList();