单个实体中的多个一对多

时间:2017-05-13 21:40:34

标签: c# entity-framework

我目前正在创建我的第一个"复合体"应用实体框架,我遇到了第一个问题。

我有两个实体:UsersEvents,定义的User可以组织Event或成为Event的参与者。我希望以这样的方式实现这些实体之间的关系:对于已定义的用户,我可以检索他组织的所有事件或检索他订阅的所有事件。

Event.cs

public virtual User Organizer { get; set; }
public List<User> Participants { get; set; }

User.cs

 public virtual ICollection<Event> EventsOrganized { get; set; }
 public virtual ICollection<Event> EventsSubscribedFor { get; set; }

如何指定EventsOrganized应引用Organizer属性,EventsSubscribedFor应引用Participants属性?

1 个答案:

答案 0 :(得分:2)

我假设您可以使用Fluent API。

在您的DbContext类中创建或添加到OnModelCreating覆盖

protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<User>()
            .HasMany(s => s.EventsOrganized)
            .WithRequired(c => c.Organizer)
            .WillCascadeOnDelete(false);

        modelBuilder.Entity<User>()
            .HasMany(s => s.EventsSubscribedFor)
            .WithMany(c => c.Participants)                
            .Map(cs =>
            {
                cs.MapLeftKey("UserId");
                cs.MapRightKey("EventId");
            });

        base.OnModelCreating(modelBuilder);
    }

发生的事情是我告诉DbContext用户实体有许多EventOrganized与所需的管理器,然后告诉DbContext不级联删除。 然后我告诉DbContext用户实体有很多EventsSubscribed ForFor Many。然后我映射左右键。这会创建一个名为“UserEvents”的表,你可以通过说cs.ToTable(“NameOfTable”)来命名它;

另外参考EntityframeworkTutorials帮助我了解了Fluent API,这些是我用来测试的实体。

public class User
{
    public User()
    {
        EventsOrganized = new HashSet<Event>();
        EventsSubscribedFor = new HashSet<Event>();
    }

    [Key]
    public int Id { get; set; }
    public string Name { get; set; }
    public virtual ICollection<Event> EventsOrganized { get; set; }
    public virtual ICollection<Event> EventsSubscribedFor { get; set; }
}

public class Event
{
    public Event()
    {
        Participants = new HashSet<User>();
    }

    [Key]
    public int Id { get; set; }
    public string Name { get; set; }

    public int OrganizerId { get; set; }
    public virtual User Organizer { get; set; }
    public ICollection<User> Participants { get; set; } 
}
相关问题