实体框架Code First:同一表格的一对多和多对多关系

10
我可以为您翻译此文。该项目中有一个用户模型和一个事件模型。事件有一个创建者(用户)和参与者(用户),因此事件与用户具有一对多的关系,同时也与同一表格具有多对多的关系。
最初,我的一对多关系是这样的:
Public class Event
{
      ...
      public int CreatedById { get; set; }
      public virtual User CreatedBy { get; set; }
      ...
}

当我添加多对多关系时,迁移不会生成多对多关系:

Public class User
{
      ...
      public virtual ICollection<Event> Events { get; set; }
      ...
}

Public class Event
{
      ...
      public int CreatedById { get; set; }
      public virtual User CreatedBy { get; set; }
      public virtual ICollection<User> Users { get; set; }
      ...
}

如果我删除了一对多关系,那么迁移将成功生成多对多关系。
有没有只使用数据注释的方法来实现这个?

你说得对,@slauma。抱歉我的英语不是我的母语,我只是尽力而为。 - Escobar5
我编辑了它,希望更清晰 - Escobar5
我不是指语言问题,而是内容(如果有任何错误消息或异常等,或者结果不是您所期望的)。无论如何,没关系,问题似乎已经解决了 :) - Slauma
2个回答

16
EF不知道要将映射到哪里。它可以是,也可以是。两者都会得到一个有效的模型。您必须通过应用[InverseProperty]属性来给EF一点提示,告诉它您想要什么:
public class User
{
    ...
    [InverseProperty("Users")]
    public virtual ICollection<Event> Events { get; set; }
    ...
}

8

对于使用Code First方法的情况,我建议您使用流畅的API而不是使用DataAnnotations,因为它会自动进行某些转换。

这样,您就可以知道您所做的确切配置。

如果我是您,我会使用以下内容:

public class EventMap : EntityTypeConfiguration<Event>
{
    public EventMap()
    {
        this.HasRequired(m => m.CreatedBy) // envent must have a creator
            .WithMany() // a user can have 0,1 or more events created by him
            .HasForeignKey(m => m.CreatedById) // specify property to be used as FK
            .WillCascadeOnDelete(true); // delete all events created by user if that specific user is deleted

        this.HasMany(m=>m.Users) // an event can have 0,1 or more participants
            .WithMany(m=>m.Events) // a user can be a participant in 0,1 or more events                
            .Map(m => m.MapLeftKey("EventId").MapRightKey("UserId")); // this will generate intermediate table to hold participant information - dbo.EventUser with EventId & UserId
            // Cascade Delete is always true for Many to Many mapping. however, it doesn't delete entry in other table, it deletes entry in Joined Table only.
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接