【发布时间】:2019-05-04 22:40:13
【问题描述】:
我想弄清楚一个 LINQ 语句 - 我对此比较陌生,所以请原谅我的无知。我想返回一个人列表,每个人都有一个兴趣列表。
person(p) 表通过 p.id = pi.personid 连接到 personinterest(pi) 表
personinterest 表连接到 interest(i) 表,pi.interestid 到 i.id。
public class Persons
{
public int Id { get; set; }
public string LastName { get; set; }
public string FirstName { get; set; }
...
public IList<Interest> PersonInterests { get; set; }
}
public class Interest
{
public string InterestName { get; set; }
}
我要返回的类是一个人,每个人的 PersonInterests 列表中填充了 0 到多个兴趣。我在下面的 Linq 语句正在返回数据,但是每个人的记录只获得一种兴趣,并且具有多个兴趣的人的人员数据重复,如下所示 linq 语句
var interests = _db.Interests;
return (from p in _db.People
join i in _db.PersonInterests on p.Id equals i.PersonId
join s in _db.Interests on i.InterestId equals s.Id
select new Persons{
Id = p.Id,
FirstName = p.FirstName,
LastName = p.LastName,
Age = p.Age,
Address = p.Address,
City = p.City,
StateAbbrev = p.StateAbbrev,
ZipCode = p.ZipCode,
PersonInterests = (from r in interests where r.Id == i.InterestId select r).ToList()
}).ToList();
结果:
{"id":1,"lastName":"Alexander","firstName":"Carson","age":23,"address":"123 4th Street","city":"Jamestown","stateAbbrev":"NV","zipCode":"65465","personInterests":[{"id":1,"interestName":"Basketball"}],"photo":null}
{"id":1,"lastName":"Alexander","firstName":"Carson","age":23,"address":"123 4th Street","city":"Jamestown","stateAbbrev":"NV","zipCode":"65465","personInterests":[{"id":2,"interestName":"Camping"}],"photo":null},
我希望数据看起来像这样:
{"id":1,"lastName":"Alexander","firstName":"Carson","age":23,"address":"123 4th Street","city":"Jamestown","stateAbbrev":"NV","zipCode":"65465","personInterests":[{"id":1,"interestName":"Basketball"}, {"id":2,"interestName":"Camping"}],"photo":null}
我已经为此苦苦挣扎了一段时间,非常感谢任何帮助。
【问题讨论】:
-
您使用的是 LINQ to SQL 还是 EF 或 EF Core?
标签: linq polymorphic-associations