EF 4.2 Code First。如何命名多对多表?

时间:2012-01-12 16:19:44

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

是否可以在多对多关系中指定表名?

示例:

class A
{
    public int Id { get; set; }
    // .....

    public virtual ICollection<B> BCollection { get; set; }
}

class B
{
    public int Id { get; set; }
    // .....

    public virtual ICollection<A> ACollection { get; set; }
}

我认为这可能有用,但显然没有。

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<A>().HasMany(x => x.BCollection).WithMany(y => y.ACollection).Map(m => m.ToTable("My_Custom_Name"));
}

1 个答案:

答案 0 :(得分:12)

尝试也可以覆盖列名。

        modelBuilder.Entity<A>()
        .HasMany(x => x.BCollection).WithMany(y => y.ACollection)
            .Map(m =>
            {
                m.ToTable("My_Custom_Name");
                m.MapLeftKey("AId");
                m.MapRightKey("BId");
            });