MrB*_*liz 24 .net c# entity-framework code-first ef-code-first
我有以下模型
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; }
}
Run Code Online (Sandbox Code Playgroud)
事件和参与者是多对多的关系,但我需要关联的另一个属性,所以我创建了一个关联实体
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; }
}
Run Code Online (Sandbox Code Playgroud)
这些是每个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});
}
}
Run Code Online (Sandbox Code Playgroud)
当我尝试通过update-database包管理器控制台中的命令初始化数据库时,出现以下错误.
System.InvalidOperationException:外键组件"FilanthropyEvent"不是"EventAttendee"类型的声明属性.验证它是否未从模型中明确排除,并且它是有效的原始属性.
我意识到我可能错过了EventAttendeesConfiguration类中的映射,但是建立这种关系的正确映射是什么?
Yul*_*dra 46
这段代码
HasMany(x => x.EventAttendees)
.WithRequired(x => x.FilanthropyEvent)
.HasForeignKey(x => x.FilanthropyEvent);
Run Code Online (Sandbox Code Playgroud)
应该
HasMany(x => x.EventAttendees)
.WithRequired(x => x.FilanthropyEvent)
.HasForeignKey(x => x.FilanthropyEventId);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9881 次 |
| 最近记录: |