LINQ to Entities - 将所有相关实体字段转换为字符串

时间:2012-02-02 12:52:04

标签: entity-framework linq-to-entities

我有类似的人物实体

PersonId
PersonName
PersonPhone

我有一个众议院实体

HouseID
HouseType
HouseSize

两个实体都与多对多关系有关。 我需要把一个人(有许多房子)的所有HouseType都变成一个字符串。

3 个答案:

答案 0 :(得分:0)

您可以使用Enumerable.Aggregate方法轻松连接序列中的多个字符串。

在您的情况下,您必须先将项目 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;

或者你可以简单地说:

var houseTypes = person.Houses
                       .Select(i => i.HouseType)
                       .AsEnumerable()
                       .Select(i => i.ToString());
return String.Join(", ", houseTypes);
houseTypes序列为空时,

将返回空字符串

<强>更新

如果您使用的是Entity Framework 4或更高版本,则可以使用built-in SQL functions之一直接在数据库中执行转换为字符串:

var houseTypes = person.Houses
                       .Select(i => SqlFunctions.StringConvert((double)i.HouseType))
                       .AsEnumerable()
return String.Join(", ", houseTypes);

答案 1 :(得分:0)

你的意思是?:

var data = context.People.Where(p => p.PersonId == <id>).SelectMany(p => p.Houses).Select(h => h.HouseType);
var result = string.Join(<separator>, data);

答案 2 :(得分:0)

var houseTypes = person.Houses
    .Select(i => i.HouseType).ToList();

return string.Join(" ", houseTypes.Select(x=>x.ToString()));