I have the following Model
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 Attendees is a many to many relationship but I needed another property on the association so I created an association entity
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; } }
These are the configurations for each FilanthropyEvent and 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}); } }
When I try and initialise the database via the update-database
command in the package manager console I get the following error.
System.InvalidOperationException: The foreign key component 'FilanthropyEvent' is not a declared property on type 'EventAttendee'. Verify that it has not been explicitly excluded from the model and that it is a valid primitive property.
I realise I'm probably missing a mapping in the EventAttendeesConfiguration
class but what would be the correct mapping to model this relationship?
This code
HasMany(x => x.EventAttendees) .WithRequired(x => x.FilanthropyEvent) .HasForeignKey(x => x.FilanthropyEvent);
Should be
HasMany(x => x.EventAttendees) .WithRequired(x => x.FilanthropyEvent) .HasForeignKey(x => x.FilanthropyEventId);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With