在实体框架中更改表名(代码优先)

时间:2013-04-06 13:48:19

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

上下文如下:

一个人可能属于一个群体(他将成为会员)并且可能是一个群组的管理员。 这在代码优先模式中建模如下:

class Group
{
     [InverseProperty("GroupsWhereIamAdmin")]
     public virtual ICollection<Person> Admins {get; set;}
     [InverseProperty("GroupsWhereIamMember")]
     public virtual ICollection<Person> Members {get; set;}
}

class Person
{
     [InverseProperty("Members")]
     public virtual ICollection<Group> GroupsWhereIamMember {get; set;}
     [InverseProperty("Admins")]
     public virtual ICollection<Group> GroupsWhereIamAdmin {get; set;}
}

问题是生成的表的名称是:

GroupPersons
GroupPersons1

我希望他们成为:

GroupAdmins
GroupMembers

如何以简单的方式实现这一目标? (即:使用属性)

1 个答案:

答案 0 :(得分:3)

所以我想这必须用Fluent API完成, 所以我删除了数据注释,即:[InverseProperty(...)],并执行了此操作:

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        // Many to many: A group has members, and a person has groups.
        modelBuilder.Entity<Group>()
            .HasMany(e => e.Members)
            .WithMany(m => m.GroupsWhereIAmMember)
            .Map(mc =>
            {
                mc.ToTable("GroupMembers");
                mc.MapLeftKey("GroupId");
                mc.MapRightKey("MemberId");
            });

        // Many to many: A group has admins, and a person has groups where he is admin
        modelBuilder.Entity<Group>()
            .HasMany(e => e.Admins)
            .WithMany(m => m.GroupsWhereIAmAdmin)
            .Map(mc =>
            {
                mc.ToTable("GroupAdmins");
                mc.MapLeftKey("GroupId");
                mc.MapRightKey("AdminId");
            });
    }