c# - Entity Framework 核心: unhandled exception

标签 c# linq entity-framework-core

我正在尝试查询应用程序中的以下实体:

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/

相关文章:

c# - 重构 OrderBy 表达式

c# - USING 语句的返回值

c# - linq to entities dynamic where 从 lambdas 构建

c# - 最小起订量和设置数据库上下文

.net-core - dotnet-core ef sql 连接

c# - 如何从Controller访问View的事件

c# - 在 SQL 中参数化 'order by'

c# - Linq - 从基于 "weight"和 "order"的列表中获取项目

sql - 链接到实体,如何修复开始解析为 sql CHARINDEX 并忽略索引

MySql 和 Entity Framework 核心 - MySqlException : Unknown column 's.CompanyId' in 'field list'