10

我的项目中有一个用户模型和一个事件模型。Event 有一个创建者(User)和一个参与者(Users),因此 Event 与 User 具有一对多的关系,并且与同一张表也具有多对多的关系。

我首先有这样的一对多关系:

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; }
      ...
}

如果我删除了一对多关系,那么迁移会成功生成多对多关系。

有没有办法只用数据注释来做到这一点?

4

2 回答 2

16

EF 不知道User.Events必须映射到哪里。它可能是Event.CreatedBy,也可能是Event.Users。两者都会产生一个有效的模型。[InverseProperty]您必须通过应用属性给 EF 一点提示您想要什么:

public class User
{
    ...
    [InverseProperty("Users")]
    public virtual ICollection<Event> Events { get; set; }
    ...
}
于 2013-02-27T20:20:00.990 回答
8

使用 Code First Approach,我总是建议使用 fluent 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.
    }
}
于 2013-04-16T06:14:47.153 回答