[英]Concatenate columns from joined table with LINQ
I have 3 EF entities: Appeal
, AppealPerson
, Person
. 我有3个 EF实体:
Appeal
, AppealPerson
, Person
。
Appeal
and Person
entities joined by AppealPerson
entity (many-to-many relation). 由
AppealPerson
实体(多对多关系)加入的Appeal
和Person
实体。 I want to select appeals with concatenated person full names. 我想选择带有串联人全名的上诉。
+----------+----------+--------------------------------------------------+
| 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 |
+----------+----------+--------------------------------------------------+
Now I'm using this query: 现在,我使用以下查询:
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>();
This query is very slow. 该查询非常慢。 List for ~500 rows generated in 30 seconds.
列出30秒内生成的约500行。 Please help to optimize query.
请帮助优化查询。
Try with joins such as: 尝试使用以下联接:
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
...
Looking at your relationships, I think you can do this with a GroupBy
clause. 查看您的关系,我认为您可以使用
GroupBy
子句来实现。 Given the formatting has to happen client-side it would be a bit less cluttered if you either had a function which wrapped up this or, even better, override ToString
on Person
考虑到格式化必须在客户端进行,如果您有一个包装了此函数的函数,或者甚至更好的是,在
Person
上重写ToString
,则将不会太混乱
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();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.