entity framework – 外键组件…不是类型的声明属性
我有以下模型
public class FilanthropyEvent : EntityBase, IDeleteable { public int Id { get; set; } public string Name { get; set; } public DateTime EventDate { get; set; } public string Description { get; set; } public decimal Target { get; set; } public decimal EntryFee { get; set; } public bool Deleted { get; set; } public ICollection EventAttendees { get; set; } } public class Attendee : EntityBase, IDeleteable { public int Id { get; set; } public string Email { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public bool MailingList { get; set; } public bool Deleted { get; set; } public ICollection EventAttendees { get; set; } }
事件和参与者是多对多的关系,但我需要关联的另一个属性,所以我创建了一个关联实体
public class EventAttendee : EntityBase { public int FilanthropyEventId { get; set; } public int AttendeeId { get; set; } public bool InActive { get; set; } public virtual Attendee Attendee { get; set; } public virtual FilanthropyEvent FilanthropyEvent { get; set; } }
这些是每个FilanthropyEvent和Attendee的配置
public class FilanthropyEventConfiguration : EntityTypeConfiguration { public FilanthropyEventConfiguration() { HasKey(x => x.Id); Property(x => x.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity); HasMany(x => x.EventAttendees).WithRequired(x => x.FilanthropyEvent).HasForeignKey(x => x.FilanthropyEvent); } } public AttendeeConfiguration() { HasKey(x => x.Id); Property(x => x.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity); HasMany(x => x.EventAttendees).WithRequired(x => x.Attendee).HasForeignKey(x => x.AttendeeId); } public class EventAttendeesConfiguration : EntityTypeConfiguration { public EventAttendeesConfiguration() { HasKey(x => new {x.FilanthropyEventId, x.AttendeeId}); } }
当我尝试通过包管理器控制台中的update-database
命令初始化数据库时,出现以下错误。
System.InvalidOperationException:外键组件“FilanthropyEvent”不是“EventAttendee”类型的声明属性。 validation它是否未从模型中明确排除,并且它是有效的原始属性。
我意识到我可能在EventAttendeesConfiguration
类中缺少一个映射,但是建立这种关系的正确映射是什么?
这段代码
HasMany(x => x.EventAttendees) .WithRequired(x => x.FilanthropyEvent) .HasForeignKey(x => x.FilanthropyEvent);
应该
HasMany(x => x.EventAttendees) .WithRequired(x => x.FilanthropyEvent) .HasForeignKey(x => x.FilanthropyEventId);