[英]LINQ to Entities - get all related entity field into a string
I have a Person Entity something like that 我有一个像这样的人实体
PersonId
PersonName
PersonPhone
I have a House Entity 我有一个房屋实体
HouseID
HouseType
HouseSize
Both Entities are related with many to many relation. 两个实体之间存在多对多关系。 I need to have all the HouseType for a person (which has many houses) into a string.
我需要将一个人(有很多房子)的所有HouseType都放入一个字符串中。
You can easily concatenate multiple strings from a sequence with the Enumerable.Aggregate method. 您可以使用Enumerable.Aggregate方法轻松地将序列中的多个字符串连接起来。
In your case you'll have to first project the list of House
entities into a list of House.HouseType
strings and then aggregate them into a single string: 你的情况,你必须第一个项目的名单
House
实体到列表House.HouseType
字符串,然后将它们合并为一个字符串:
var houseTypes = person.Houses.Select(i => i.HouseType).AsEnumerable();
var emptyResult = "0";
return houseTypes.Any() ?
houseTypes.Select(i => i.ToString())
.Aggregate((current, next) => current + ", " + next) :
emptyResult;
Alternatively you could simply say: 或者,您可以简单地说:
var houseTypes = person.Houses
.Select(i => i.HouseType)
.AsEnumerable()
.Select(i => i.ToString());
return String.Join(", ", houseTypes);
which will return an empty string when the houseTypes
sequence is empty. 当
houseTypes
序列为空时,它将返回一个空字符串 。
Update: 更新:
If you're using Entity Framework 4 or above, you can use one of the built-in SQL functions to perform the conversion to string directly in the database: 如果您使用的是Entity Framework 4或更高版本,则可以使用内置的SQL函数之一直接在数据库中执行到字符串的转换:
var houseTypes = person.Houses
.Select(i => SqlFunctions.StringConvert((double)i.HouseType))
.AsEnumerable()
return String.Join(", ", houseTypes);
You mean something like?: 您的意思是?:
var data = context.People.Where(p => p.PersonId == <id>).SelectMany(p => p.Houses).Select(h => h.HouseType);
var result = string.Join(<separator>, data);
var houseTypes = person.Houses
.Select(i => i.HouseType).ToList();
return string.Join(" ", houseTypes.Select(x=>x.ToString()));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.