实体框架——外键组件…不是类型上声明的属性

本文关键字:类型 声明 属性 框架 组件 实体 | 更新日期: 2023-09-27 18:13:10

我有以下模型

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

Events and participants是一个多对多关系,但是我需要另一个关联属性,所以我创建了一个关联实体

 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<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命令初始化数据库时,我得到以下错误:

系统。InvalidOperationException:外键组件"FilanthropyEvent"不是类型"EventAttendee"的声明属性。验证它没有被显式地从模型中排除,并且它是一个有效的原语属性。

我意识到我可能在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);