EF Code First,指定关系表?

时间:2013-09-09 06:03:55

标签: ef-code-first

类:

public class Action
{
    public long ID{ get; set; }
    public string Name{ get; set; }

    public virtual ICollection<User> Users{ get; set; }
}


public class User
{
    public long ID{ get; set; }
    public string Name{ get; set; }

    public virtual ICollection<Action> Actions{ get; set; }
}

表:

Actions 
| ID | Name |

Users  
|ID | Name |

ActionUsers 
| Action_ID | User_ID |

请注意,ActionUser具有多对多关系。

假设EF可以成功映射上面的示例(我简化了原始代码),那么我决定执行以下操作:

  • 将表格ActionUsers重命名为Permissions
  • Action班级成员,Users重命名为PermittedUsers
  • User班级成员,Actions重命名为Permissions

在映射PermissionsActionUsers时,如何告诉EF将User.Permissions用作关系表而不是Action.PermittedUsers?我可以在不使用Fluent API的情况下实现所需的配置吗?

1 个答案:

答案 0 :(得分:2)

使用Fluent API:

public class Action
{
    public long ID{ get; set; }
    public string Name{ get; set; }

    public virtual ICollection<User> PermittedUsers{ get; set; }
}


public class User
{
    public long ID{ get; set; }
    public string Name{ get; set; }

    public virtual ICollection<Action> Permissions{ get; set; }
}

您只需覆盖OnModelCreating方法:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
  {
    modelBuilder.Entity<Action>().
      HasMany(c => c.PermittedUsers).
      WithMany(p => p.Permissions).
      Map(
       m =>
       {
         m.MapLeftKey("Action_ID");
         m.MapRightKey("User_ID");
         m.ToTable("Permissions");
       });
  }

如果您想拥有自己的命名约定,可以将Permission表定义为类:

public class Permissions
{

    [ForeignKey("Action")]
    public int Action_ID { get; set; }
    public Action Action { get; set; }


    [ForeignKey("User")]
    public int User_ID { get; set; }
    public User User { get; set; }
}

// context
public class MyContext : DbContext
{
    public DbSet<Action> Actions { get; set; }
    public DbSet<User> Users { get; set; }
    public DbSet<Permissions> Permissions { get; set; }
}