简体   繁体   English

如何使用 LINQ 和 EF Core 进行一对多

[英]How to do a 1 to many using LINQ and EF Core

In my Place Repository I want to bring all the Place records including any Registration records for each Place , even if there are no records in the Registration table.在我的Place Repository中,我想带上所有Place记录,包括每个Place的任何Registration记录,即使Registration表中没有记录。

Currently I have:目前我有:

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

Results in the following error:导致以下错误:

InvalidOperationException: The LINQ expression '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)' could not be translated, Either rewrite the query in a form that can be translated, or switch to client evaluation explicitly by inserting a call to 'AsEnumerable', 'AsAsyncEnumerable', 'ToList'. 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")IdNull : objB. (object)EF,Property(r. "PlaceId"))).Where(r => r.PlaceId == r.Id)' 无法翻译,要么以可翻译的形式重写查询,或通过插入对“AsEnumerable”、“AsAsyncEnumerable”、“ToList”的调用显式切换到客户端评估。 or 'ToListAsync'.或“ToListAsync”。 See https://go.microsoft.com/fwlink/?linkid=2101038 for more information.有关详细信息,请参阅https://go.microsoft.com/fwlink/?linkid=2101038

The Model: Model:

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

Just change the include function to this只需将包含 function 更改为此

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM