entity framework code first double one to one relationship
-
04-06-2021 - |
Question
class Event{
int? EventID{get;set;}
int? FirstParticipantID{get;set;}
Participant FirstParticipant{get;set;}
int? SecondParticipantID{get;set;}
Participant SecondParticipant{get;set;}
int? CreatedByID{get;set;}
User CreatedBy{get;set;}
}
class Participant{
int? ParticipantID{get;set;}
List<Event> Events{get;set;}
int? CreatedByID{get;set;}
User CreatedBy{get;set;}
}
protected override void OnModelCreating(DbModelBuilder modelBuilder){
modelBuilder.Entity<Event>().HasRequired(m => m.FirstParticipant).WithMany(m => m.Events).HasForeignKey(m => m.FirstParticipantID);
modelBuilder.Entity<Event>().HasRequired(m => m.SecondParticipant).WithMany(m => m.Events).HasForeignKey(m => m.SecondParticipantID);
modelBuilder.Entity<Event>().HasRequired(m => m.CreatedBy);
modelBuilder.Entity<Participant>().HasRequired(m => m.CreatedBy);
}
It seems very clear to me, but EF (and sql) keeps complaining, no matter what moves I make to the hasmanny/hasrequired stuff. I can't even find google help cause I don't know the name of what I'm trying to implement (double one to one???!!!)
The idea is that an Event must have 2 not null Participants (first & second only, not many) and that each Participant may have many Events
Thanks
Solution
There are multiple problems in your code:
- PK cannot be nullable
- FK cannot be nullable if you want to define the relation as Required
- When you define two relations with
Participant
you need two navigation properties - you cannot map two relations into singleEvents
property - You didn't complete your mapping of
CreatedBy
in bothEvent
andParticipant
Try this:
public class Event{
public int EventID {get;set;}
public int FirstParticipantID{get;set;}
public Participant FirstParticipant{get;set;}
public int SecondParticipantID{get;set;}
public Participant SecondParticipant{get;set;}
public int CreatedByID{get;set;}
public User CreatedBy{get;set;}
}
public class Participant{
public int ParticipantID {get;set;}
public int CreatedByID {get;set;}
public User CreatedBy {get;set;}
public ICollection<Event> FristEvents { get; set; }
public ICollection<Event> SecondEvents { get; set; }
}
protected override void OnModelCreating(DbModelBuilder modelBuilder){
modelBuilder.Entity<Event>()
.HasRequired(m => m.FirstParticipant)
.WithMany(m => m.FirstEvents)
.HasForeignKey(m => m.FirstParticipantID);
modelBuilder.Entity<Event>()
.HasRequired(m => m.SecondParticipant)
.WithMany(m => m.SecondEvents)
.HasForeignKey(m => m.SecondParticipantID);
modelBuilder.Entity<Event>()
.HasRequired(m => m.CreatedBy)
.WithMany()
.HasForeignKey(m => m.CreatedByID);
modelBuilder.Entity<Participant>()
.HasRequired(m => m.CreatedBy)
.WithMany()
.HasForeignKey(m => m.CreatedByID);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow