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

这对我来说似乎很清楚,但 EF(和 sql)一直在抱怨,无论我对 hasmanny/hasrequired 的东西采取什么行动。我什至找不到谷歌帮助,因为我不知道我要实现的名称(一对一???!!!)

这个想法是一个事件必须有 2 个不为空的参与者(只有第一个和第二个,不多),并且每个参与者可能有很多事件

谢谢

4

1 回答 1

2

您的代码中有多个问题:

  • PK 不能为空
  • 如果要将关系定义为必需,则 FK 不能为空
  • 当您定义两个关系时,Participant您需要两个导航属性 - 您不能将两个关系映射到单个Events属性
  • 你没有完成你的CreatedBy映射EventParticipant

试试这个:

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);  
}
于 2012-04-27T08:16:25.753 回答