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

后端 未结 2 1919
醉话见心
醉话见心 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

    If you don't use (or cannot use) EF migrations you can use custom initializer as mentioned in this answer. The custom initializer will execute a Seed method after creating the database = only once when database doesn't exist. If you need to incrementally develop the database initializer itself will not help you (that is what migrations are for).

    0 讨论(0)
  • 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

    0 讨论(0)
提交回复
热议问题