【问题标题】:Entity Framework Core : unhandled exception实体框架核心:未处理的异常
【发布时间】:2018-06-29 17:54:24
【问题描述】:

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

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:包含属性 lambda 表达式“p => p.Reservations”无效。该表达式应表示属性访问:'t => t.MyProperty'。要定位在派生类型上声明的导航,请指定目标类型的显式类型 lambda 参数,例如'(Derived d) => d.MyProperty'.

我在这里做错了什么吗?

【问题讨论】:

  • 你试过 _context.Persons.Include("Reservations").ToListAsync()

标签: c# linq entity-framework-core


【解决方案1】:

Person.Reservations 是一个字段,而convention 的 EF Core(虽然可以使用支持字段进行具体化)仅映射 属性

按照惯例,带有 getter 和 setter 的公共属性将包含在模型中。

简单的改变

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

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

问题应该解决了。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-22
    • 1970-01-01
    • 2013-03-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多