为什么 EF 在<Type>保存包含相关对象列表的对象(1 到多)时尝试将列表转换为类型?



当我尝试通过调用context.Consumption.Add(myConsumption)然后context.SaveChanges()来保存消耗对象时,我得到一个System.InvalidCastException。我不知道为什么EF要List<Payment>投射到Payment,因为消费的支付属性是List<Payment>类型。

public class Consumption {
public int Id { get; set; }
...
public virtual List<Payment> Payments { get; set; }
}
public class Payment {
...
[ForeignKey("Id")]
public Consumption Consumption { get; set; }
}

我认为你的事情有点古怪

假设您有以下设计

public class Consumption 
{
public int Id { get; set; }
...
public virtual List<Payment> Payments { get; set; }
}
public class Payment {
public int Id { get; set; }
public Consumption Consumption { get; set; }
public int ConsumptionId { get; set; }
}

EF 足够聪明,可以根据命名约定找出关系和数据库基架

但是,如果需要使用批注,则需要决定如何向 EF 告知您的关系。

public class Payment {
public int Id { get; set; }
public Consumption Consumption { get; set; }
[ForeignKey("Consumption")] // point to the FK to the navigation property
public int ConsumptionId { get; set; }
}

public class Payment {
public int Id { get; set; }
[ForeignKey("ConsumptionId")] // point to the navigation property to the FK
public Consumption Consumption { get; set; }
public int ConsumptionId { get; set; }
}

public class Consumption 
{
public int Id { get; set; }
...
[ForeignKey("ConsumptionId")]  // Point to the dependent FK
public virtual List<Payment> Payments { get; set; }
}

我怀疑在您的数据库中(这应该很容易检查),您的Consumption表中只有一个单数foreign key用于payment

您似乎指向付款表格的Primary key。然而,撇开思考不谈,EF 甚至让你进行此迁移让我感到惊讶(如果我没看错的话)

相关内容

  • 没有找到相关文章

最新更新