5

我正在使用带有 .NET Framework 4.0 的 Entity Framework 4.4 构建 ASP MVC 网站

我在我的模型中添加了多对多关系,如下所示:

  public class User {
    public int UserID { get; set; }
    public string Username { get; set; }
    public virtual ICollection<Tenant> Tenants { get; set; }
  }


  public class Tenant {
    public string TenantID { get; set; }
    public string Name { get; set; }
    public virtual ICollection<User> Users { get; set; }
  }

当我运行Add-Migration命令时,我得到了这个迁移类(我删除了 Down 方法)

  public partial class TenantUsersManyToManyMigration : DbMigration
    {
        public override void Up()
        {
            CreateTable(
                "dbo.UserTenants",
                c => new
                    {
                        User_UserID = c.Int(nullable: false),
                        Tenant_TenantID = c.String(nullable: false, maxLength: 128),
                    })
                .PrimaryKey(t => new { t.User_UserID, t.Tenant_TenantID })
                .ForeignKey("dbo.Users", t => t.User_UserID, cascadeDelete: true)
                .ForeignKey("dbo.Tenants", t => t.Tenant_TenantID, cascadeDelete: true)
                .Index(t => t.User_UserID)
                .Index(t => t.Tenant_TenantID);
        }
  }
  1. 为什么 TenantID 和 UserID 的字段名称分别是 User_UserID 和 Tenant_TenantID 而不是 UserID 和 TenantID。

  2. 如何更改默认迁移脚手架(或我的模型)以使 cascadeDelete 为假?(目前我只是手动更改它)。

4

2 回答 2

7

您可以使用流利的表示法以您想要的方式创建映射表。在您的 DbContext 类中,使用以下内容覆盖 OnModelCreating:

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<User>()
            .HasMany(u => u.Tenants)
            .WithMany(t => t.Users)
            .Map(m =>
                {
                    m.ToTable("UserTenants");
                    m.MapLeftKey("UserId");
                    m.MapRightKey("TenantId");
                });
    }

此外,使用 fluent 时,如果要在单个表上禁用级联删除,可以在映射属性时使用 .WillCascadeDelete(false)。这是MSDN上关于如何使用流利符号的精彩文章。

于 2012-09-12T13:09:06.113 回答
4

您可以通过这种方式删除级联删除约定:

using System.Data.Entity.ModelConfiguration.Conventions;

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();
}

然后看看脚手架有没有变化。我个人从未使用过它。

此外,Microsoft(有点)在标题下的此链接中解释了 FK 命名约定Foreign Keys

于 2012-09-12T12:23:44.523 回答