【问题标题】:Change table name in Entity Framework (Code First)在实体框架中更改表名(代码优先)
【发布时间】:2013-04-06 13:48:19
【问题描述】:

上下文如下:

一个人可能属于一个组(他将是一个成员)并且可能是一个组的管理员。 这在代码优先中是这样建模的:

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;}
}

问题是生成的表的名字是这些:

组人
GroupPersons1

我希望他们成为:

组管理员
群组成员

我怎样才能以简单的方式实现这一目标? (即:使用属性)

【问题讨论】:

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


【解决方案1】:

所以我想这必须通过 Fluent API 来完成, 所以我删除了数据注释,即:[InverseProperty(...)]'s,然后这样做:

    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");
            });
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-07-14
    • 2017-07-05
    • 1970-01-01
    • 2017-09-01
    • 2014-05-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多