问题描述
我有以下课程:
public class User
{
public Guid Id { get; set; }
public string Name { get; set; }
}
public class ParentEntity
{
public Guid Id { get; set; }
public string SomeProperty { get; set; }
public ICollection<ChildEntity> ChildEntities { get; set; }
}
public class ChildEntity
{
public Guid Id { get; set; }
public int Vote { get; set; }
public Guid UserId { get; set; }
}
public class ReturnedParentDto
{
public Guid Id { get; set; }
public string SomeProperty { get; set; }
public int Vote { get; set; }
}
我希望能够返回ParenEntities的完整列表,但是要获取User类的ID(UserClassId),然后过滤ParentUser的ICollection,其中UserUid = UserClassId,因此始终仅返回1 ChildEntity。然后,我想从返回的ChildEntity中提取特定字段,并将其与ParentEntity字段合并。最终结果应类似于ReturnedParentDto。
我想要像这样
ParentEntities.Include(v => v.ChildEntities).ToList()
这在EF Core 5中似乎可行,但我的项目在3.1中。
解决方法
您可以按照以下步骤进行操作
方法1:
var result = result = parentEntities.Include(x => x.ChildEntities.Where(y => y.UserId == userId))
.Select(x => new ReturnedParentDto {
Id = x.Id,SomeProperty = x.SomeProperty,Vote = x.ChildEntities.FirstOrDefault()?.Vote // userId is the variable here
});
方法2:
var result = parentEntities.Select(x =>
new ReturnedParentDto {
Id = x.Id,Vote = x.ChildEntities.FirstOrDefault(y => y.UserId == userId)?.Vote // userId is the variable here
});