【问题标题】:How to do a 1 to many using LINQ and EF Core如何使用 LINQ 和 EF Core 进行一对多
【发布时间】:2021-08-20 13:30:56
【问题描述】:

在我的Place Repository中,即使Registration 表中没有记录,我也想为每个Place 带来所有Place 记录,包括任何Registration 记录。

目前我有:

public IEnumerable<Place> Places
{
   get
   {
      return _appDbContext.Places.Include(r => r.Registrations.Where(q => q.PlaceId == r.Id));
   }
}

导致以下错误:

InvalidOperationException: LINQ 表达式 'DbSet() .Where(r => EF.Property(EntityShaperExpression: EntityType: Place ValueBufferExpression: ProjectionBindingExpression: Outer.Outer.Outer.Outer.Outer.Outer.Outer.Outer IsNullable: False , "Id") != null && object.Equals(objA: (object)EF.Property(EntityShaperExpression: EntityType: Place ValueBufferExpression: ProjectionBindingExpression: Outer.Outer.Outer.Outer.Outer.Outer.Outer.Outer IsNullable: False, " Id"), objB: (object)EF.Property(r, "PlaceId"))) .Where(r => r.PlaceId == r.Id)' 无法翻译。以可翻译的形式重写查询,或通过插入对“AsEnumerable”、“AsAsyncEnumerable”、“ToList”或“ToListAsync”的调用显式切换到客户端评估。请参阅https://go.microsoft.com/fwlink/?linkid=2101038 了解更多信息。

模型:

public class Place
{
   private const int _annualFiguresDueWithinDays = 90;
   public int Id { get; set; }
   [Required(ErrorMessage = "Please enter in the Place's name.")]
   [MaxLength(100, ErrorMessage = "The maximum length for the place name is 100 characters.")]
   public string PlaceName { get; set; }
   public IEnumerable<Registration> Registrations { get; set; }
}

public class Registration
{
   public int Id { get; set; }
   [ForeignKey("PlaceId")]
   public int PlaceId { get; set; }
   public DateTime? RegistrationDate { get; set; }
   public bool IsFirstRegistration { get; set; }
}

【问题讨论】:

  • Include(r =&gt; r.Registrations) 就够了。
  • 感谢 Mat J,这行得通。

标签: c# linq asp.net-core-5.0 ef-core-5.0


【解决方案1】:

把include函数改成这个就行了

public IEnumerable<Place> Places
{
   get
   {
      return _appDbContext.Places.Include(r => r.Registrations));
   }
}

【讨论】:

  • EF 将从导航属性配置中生成正确的 SQL 连接过滤器约束。
猜你喜欢
  • 2019-11-26
  • 1970-01-01
  • 2019-07-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-21
  • 2017-10-26
  • 1970-01-01
相关资源
最近更新 更多