为什么EF在保存带有相关对象列表(1到多个)的对象时尝试将List <type>转换为Type?

时间:2018-02-09 00:47:53

标签: c# entity-framework code-first

当我尝试通过调用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; }
    }

1 个答案:

答案 0 :(得分:0)

我认为你的东西有些怪异

假设您有以下设计

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

我怀疑在你的数据库中(这应该很容易检查)你的foreign keyConsumption中只有一个payment单数{/ 1}}

您似乎指向付款表的Primary key。除了冥思之外,令我惊讶的是,EF甚至允许你进行这种迁移(如果我正确地阅读它)