Fluent LINQ EF Core-选择过滤的子属性

问题描述

我有以下课程:

  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
 });

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...