EF 6 Code First迁移公约

时间:2015-01-18 03:29:13

标签: entity-framework ef-migrations conventions

我引用了另一个SO问题,根据我想要的惯例重命名我的外键属性。

How do I remove underscore of foreign key fields in code first by convention

我发现这些约定仅在运行时受到尊重,并且在脚手架代码首次迁移时不会被使用。

如果它能够尊重我的FK命名约定,那么我可以节省一些时间,而不必调整每次生成的迁移。

供参考:

public class ApplicationUser : AbstractEntity
{
    public EmailAddress PrimaryEmail { get; set; }
}

public class EmailAddress : AbstractEntity
{
    public string Value { get; set; }
}

public class MyDbContext : DbContext
{
    protected override void OnModelCreating(DbModelBuilder mb)
    {
        mb.Conventions.AddBefore<ForeignKeyIndexConvention>(new MyForeignKeyNamingConvention());
        mb.Conventions.Remove<PluralizingTableNameConvention>(); 

        //complex types here
        mb.Configurations.Add(new PersonNameConfiguration());

        //entity types here
        mb.Configurations.Add(new ApplicationUserConfiguration());
        mb.Configurations.Add(new EmailAddressConfiguration());

        base.OnModelCreating(mb);
    }

    public IDbSet<ApplicationUser> Users { get; set; }
}

因此,对于上面的参与者和显示的上下文,我去支持迁移以添加电子邮件表。它创建了以下内容:

public partial class CreateEmailAddresses : DbMigration
{
    public override void Up()
    {
        CreateTable(
            "dbo.EmailAddress",
            c => new
                {
                    Id = c.Int(nullable: false, identity: true),
                    Value = c.String(nullable: false, maxLength: 1023),
                    IsRemoved = c.Boolean(nullable: false),
                    CreatedDate = c.DateTimeOffset(nullable: false, precision: 7),
                    ModifiedDate = c.DateTimeOffset(precision: 7),
                    RemovedDate = c.DateTimeOffset(precision: 7),
                })
            .PrimaryKey(t => t.Id);

        AddColumn("dbo.ApplicationUser", "PrimaryEmail_IdValue", c => c.Int(nullable: false));
        CreateIndex("dbo.ApplicationUser", "PrimaryEmail_IdValue");
        AddForeignKey("dbo.ApplicationUser", "PrimaryEmail_IdValue", "dbo.EmailAddress", "Id", cascadeDelete: true);
    }

    public override void Down()
    {
        DropForeignKey("dbo.ApplicationUser", "PrimaryEmail_IdValue", "dbo.EmailAddress");
        DropIndex("dbo.ApplicationUser", new[] { "PrimaryEmail_IdValue" });
        DropColumn("dbo.ApplicationUser", "PrimaryEmail_IdValue");
        DropTable("dbo.EmailAddress");
    }
}

我在运行时测试过,确实使用了外键命名约定,并按照我想要的方式运行。但EF的脚手架部分并没有看到它。

我只是在寻找一些东西?

编辑要明确我希望迁移生成外键名称而不使用&#34; _&#34;在名字里。

0 个答案:

没有答案