我有以下模型
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<EventAttendee> 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<EventAttendee> 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和参加者的配置
public class FilanthropyEventConfiguration : EntityTypeConfiguration<FilanthropyEvent>
{
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<EventAttendee>
{
public EventAttendeesConfiguration()
{
HasKey(x => new {x.FilanthropyEventId, x.AttendeeId});
}
}
当我尝试通过包管理器控制台中的update-database
命令初始化数据库时,出现以下错误。
System.InvalidOperationException:外键组件&#39; FilanthropyEvent&#39;不是类型&#39; EventAttendee&#39;的声明属性。验证它是否未从模型中明确排除,并且它是有效的原始属性。
我意识到我可能错过了EventAttendeesConfiguration
类中的映射,但是建立这种关系的正确映射是什么?
答案 0 :(得分:44)
此代码
HasMany(x => x.EventAttendees)
.WithRequired(x => x.FilanthropyEvent)
.HasForeignKey(x => x.FilanthropyEvent);
应该是
HasMany(x => x.EventAttendees)
.WithRequired(x => x.FilanthropyEvent)
.HasForeignKey(x => x.FilanthropyEventId);