我有一个可以有多个事件日期的事件表。我已经对这个错误进行了一些研究,但看起来我已经正确设置了所有内容,但是我对代码第一种方法不熟悉,而且我认为我的困惑在于覆盖了OnModelCreating
One or more validation errors were detected during model generation:
Event_EventDates_Source_Event_EventDates_Target: : The number of properties in the Dependent and Principal Roles in a relationship constraint must be identical.
[Table("EventDates")]
public class EventDate
{
[Key, Column(Order=1)]
public int EventDateId { get; set; }
[Key, Column(Order = 2)]
public DateTime EventDateStart { get; set; }
public DateTime? EventEnd { get; set; }
public string TicketPurchaseUrl { get; set; }
}
[Table("Events")]
public class Event
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int EventId { get; set; }
...
public int EventDateId { get; set; }
public DateTime EventDateStart { get; set; }
[ForeignKey("EventDateId, EventDateStart")]
public virtual ICollection<EventDate> EventDates { get; set; }
}
答案 0 :(得分:1)
对于您描述的业务逻辑,您的模型有点奇怪。如果Event
可以有多个EventDates
,则Event
中的外键不应该引用EventDate
,反之亦然:{{1}中的外键} {}引用EventDate
,也可能是Event
中的导航属性Event
:
EventDate
按惯例,[Table("EventDates")]
public class EventDate
{
public int EventDateId { get; set; }
public int EventId { get; set; }
[ForeignKey("EventId")]
public Event Event { get; set; }
public DateTime EventDateStart { get; set; }
public DateTime? EventEnd { get; set; }
public string TicketPurchaseUrl { get; set; }
}
[Table("Events")]
public class Event
{
public int EventId { get; set; }
public virtual ICollection<EventDate> EventDates { get; set; }
}
和EventDate.EventDateId
将成为密钥,它们将自动生成。我建议您省去Event.EventId
中DateTime
作为复合键的一部分的麻烦。如果你真的不需要这样的复合键,只需要EventDate
身份作为键就可以保持简单。