【问题标题】:Entity Framework Code First: One-to-Many and Many-to-Many relationships to same table实体框架代码优先:对同一张表的一对多和多对多关系
【发布时间】:2013-02-13 19:30:54
【问题描述】:

我的项目中有一个用户模型和一个事件模型。 Event 有一个 creator(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; }
      ...
}

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

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

【问题讨论】:

  • 你是对的@slauma,原谅我的英语不是我的母语,我只是尽力做到最好。
  • 我编辑了,希望更清楚
  • 我说的不是语言的东西,而是内容(如果有任何错误信息或异常等,或者如果结果不是你所期望的等等)。无论如何,没关系,问题似乎已经解决了:)

标签: entity-framework ef-code-first code-first entity-framework-migrations


【解决方案1】:

对于 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.
    }
}

【讨论】:

    【解决方案2】:

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

    public class User
    {
        ...
        [InverseProperty("Users")]
        public virtual ICollection<Event> Events { get; set; }
        ...
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-04-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-17
      相关资源
      最近更新 更多