EF代码首先 - 多对多关系映射表与额外列

时间:2015-06-17 18:48:20

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

我有一个用户模型和一个组模型。用户和组共享多对多关系。当我将其转换为表格时,我希望有一个映射表。我正在使用以下内容来实现这一目标。

modelBuilder.Entity<UserGroup>()
        .HasMany(a => a.Users)
         .WithMany(b => b.UserGroup)

         .Map(mc =>
         {

             mc.ToTable("UserUserGroupMapping");
             mc.MapLeftKey("UserId");
             mc.MapRightKey("UserGroupId");

         });

这将创建一个以UserId和UserGroupId为列的表。但是我的挑战很少,

我希望能够在此表中添加一个Identity列,并为表添加一些审计列(例如:创建者,创建日期)。我不知道该怎么做。

任何人都可以帮助我吗?

由于

1 个答案:

答案 0 :(得分:8)

如果您执行以下操作,我认为它会起作用:

  1. 删除您在上面的代码段中显示的配置
  2. 添加映射表并配置其表名以匹配原始表名。

    // name this whatever you want
    class UserUserGroupMapping
    {
        public UserUserGroupMappingId { get; set; }
        public int UserId { get; set; }
        public virtual User User { get; set; } 
        public int UserGroupId { get; set; }
        public virtual UserGroup UserGroup { get; set; } 
        // other properties
    }
    

    modelBuilder.Entity<UserUserGroupMapping>()
        .HasKey(um => um.UserUserGroupMappingId)
        .ToTable("UserUserGroupMapping");
    
  3. UserUserGroup替换多对多集合属性,并将其替换为一对多关联

    class User
    {
        // other properties
        // remove this:
        // public virtual ICollection<UserGroup> UserGroup { get; set; }
        public virtual ICollection<UserUserGroupMapping> UserGroupMappings { get; set; }
    }
    
    class UserGroup
    {
        // other properties
        // remove this:
        // public virtual ICollection<User> Users { get; set; }
        public virtual ICollection<UserUserGroupMapping> UserMappings { get; set; }
    }
    

    modelBuilder.Entity<UserUserGroupMapping>()
        .HasRequired(um => um.UserGroup).WithMany(g => g.UserMappings)
        .HasForeignKey(um => um.UserGroupId);
    
    modelBuilder.Entity<UserUserGroupMapping>()
        .HasRequired(um => um.User).WithMany(g => g.UserGroupMappings)
        .HasForeignKey(um => um.UserId);
    
  4. 使用程序包管理器Add-Migration并删除可能尝试删除旧表并创建新表的scaffolded迁移中的任何内容。迁移至少需要(我可能会遗漏一些):

    • DropPrimaryKey表示原始键列
    • AddColumn用于新列(新主键列为Int(identity:true, nullable: false)
    • AddPrimaryKey代表新的关键列
  5. 然后,您可以使用this answer中列出的方法来检索实体。