【问题标题】:Howto config Code First Entity Framework Many-to-Many mapping table?如何配置 Code First Entity Framework 多对多映射表?
【发布时间】:2013-06-13 15:53:07
【问题描述】:

从我在网上和编程实体框架 CodeFirst 书中看到的示例中,当您在两个类上都有一个集合时,EF 将创建一个具有两个主键的映射表。 但是我怎样才能在这个表中添加一些额外的字段呢?例如,我有以下实体和上下文

public class User
{
    [Key]
    public Guid Id { get; set; }
    public String Name { get; set; }
    public virtual ICollection<Role> Roles { get; set; }
}

public class Role
{
    [Key]
    public Guid Id { get; set; }
    public String Name { get; set; }
    public virtual ICollection<User> Users { get; set; }
}

class MyContext : DbContext
{
    public MyContext (string connString)
        : base(connString)
    {
    }

    public DbSet<User> Users { get; set; }
    public DbSet<Role> Roles { get; set; }
}

访问此上下文将导致创建具有 3 个表的数据库:Users、Roles 和 UserRoles - 具有两个 Guid 字段的多对多映射表。

我想在此表中添加一些额外的字段 - DateTime AssignmentDate。 如果我添加新实体

public class UserRoles
{
    [Key]
    public Guid User_Id { get; set; }
    [Key]
    public Guid Role_Id { get; set; }
    public DateTime AssignmentDate { get; set; }
}

class MyContext : DbContext
{
    public MyContext (string connString)
        : base(connString)
    {
    }

    public DbSet<User> Users { get; set; }
    public DbSet<Role> Roles { get; set; }
    public DbSet<UserRoles> UserRoles { get; set; }
}

结果是数据库中多了一张表。 但我想修改自动创建的表。 我该怎么做?

谢谢。

【问题讨论】:

    标签: c# ef-code-first


    【解决方案1】:

    您必须使用单独的类 UserRoles,但在您的 UserRole 类中将关系更改为使用 IList&lt;UserRole&gt; 而不是直接相互引用。

    您不能配置默认的多对多表,因为它总是自动生成的,只有两个主键列。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-20
      • 1970-01-01
      • 2011-04-06
      • 1970-01-01
      • 2021-02-08
      相关资源
      最近更新 更多