简体   繁体   中英

Entity Framework Core : unhandled exception

I'm trying to query the following entities in my application:

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

I'm using this query:

public async Task<IEnumerable<Person>> GetPersonsAndReservations()
{
    return await _context.Persons.Include(p => p.Reservations).ToListAsync();
}

I keep getting the following exception:

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, Eg '(Derived d) => d.MyProperty'.

Is there anything I'm doing wrong here?

The Person.Reservations is a field while EF Core (although can use backing fields for materialization) by convention maps only properties :

By convention, public properties with a getter and a setter will be included in the model.

Simply change

public ICollection<Reservation> Reservations =
    new List<Reservation>();

to

public ICollection<Reservation> Reservations { get; set; } =
    new List<Reservation>();

and the problem should be solved.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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