Entity Framework Core : unhandled exception

c# entity-framework-core linq

Question

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

Is there anything I'm doing wrong here?

1
2
6/29/2018 6:30:33 PM

Accepted Answer

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.

3
6/29/2018 6:14:26 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow