我正在尝试查询应用程序中的以下实体:
public class Reservation
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int ReservationId { get; set; }
public int PersonId { get; set; }
[ForeignKey("PersonId")]
public Person Person { get; set; }
[ForeignKey("FilmShowId")]
public FilmShow FilmShow { get; set; }
public int FilmShowId { get; set; }
}
public class Person
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int PersonId { get; set; }
[Required]
[MaxLength(255)]
public string FirstName { get; set; }
[Required]
[MaxLength(255)]
public string LastName { get; set; }
public string Email { get; set; }
public ICollection<Reservation> Reservations =
new List<Reservation>();
}
我正在使用此查询:
public async Task<IEnumerable<Person>> GetPersonsAndReservations()
{
return await _context.Persons.Include(p => p.Reservations).ToListAsync();
}
我不断收到以下异常:
ArgumentException: The Include property lambda expression 'p => p.Reservations' is invalid. The expression should represent a property access: 't => t.MyProperty'. To target navigations declared on derived types, specify an explicitly typed lambda parameter of the target type, E.g. '(Derived d) => d.MyProperty'.
我在这里做错了什么吗?
最佳答案
Person.Reservations
是一个字段,而 EF Core(尽管可以使用支持字段来实现)convention仅映射属性:
By convention, public properties with a getter and a setter will be included in the model.
简单地改变
public ICollection<Reservation> Reservations =
new List<Reservation>();
至
public ICollection<Reservation> Reservations { get; set; } =
new List<Reservation>();
问题应该得到解决。
关于c# - Entity Framework 核心: unhandled exception,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51107114/