EF5 Code First: Detect if it creates a database so I can run ALTER statements

后端 未结 2 1921
醉话见心
醉话见心 2021-01-29 01:12

I am new with Entity Framework 5. Our team is using Code First workflow.

Before I\'ll start with my main question, let me first show you what I have tr

2条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-29 01:26

    You should take a look at Code First Migrations, more specific at the Data Motion / Custom SQL and later sections - this is might the way to achieve your desired result. Your migration class can look like this:

    public partial class AddUniqueConstrains : DbMigration
    {
        public override void Up()
        {
            Sql("ALTER TABLE Account ADD CONSTRAINT UQ_Account_AccountNumber UNIQUE(AccountNumber)");
            Sql("ALTER TABLE Account ADD CONSTRAINT UQ_Account_GUID UNIQUE(GUID)");
        }
    
        public override void Down()
        {
            Sql("ALTER TABLE Account DROP CONSTRAINT UQ_Account_AccountNumber UNIQUE");
            Sql("ALTER TABLE Account DROP CONSTRAINT UQ_Account_GUID");
        }
    }
    

    You can also explore other options described in answers to this question: Unique Constraint in Entity Framework Code First

提交回复
热议问题