2013-04-18 11 views
0

我是Entity Framework 5的新成員。我們的團隊正在使用Code First工作流程。EF5 Code First:檢測它是否創建數據庫,以便我可以運行ALTER語句

之前,我會用我的主要問題入手,讓我先告訴你我已經試過的所有時間:D最終評論)

public class MyDBContext : CDBContext 
{ 
    public MyDBContext() : base(connString) { } 

    public MyDBContext(string connStr) : base(connStr) { } 

    protected override void OnModelCreating(DbModelBuilder modelBuilder) 
    { 
     // removes some conventions 
     modelBuilder.Conventions.Remove<ManyToManyCascadeDeleteConvention>(); 
     // ........ 

     // model configurations which contains mappings 
     modelBuilder.Configurations.Add(new AccountConfiguration()); 
     // ........ 

     // calls base OnModelCreating 
     base.OnModelCreating(modelBuilder); 
    } 

    // list of all Entity 
    public DbSet<Account> Account { get; set; } 
} 

MyDBContext是我創建的類,從CBDContext繼承包含重寫方法,並且也從DBContext繼承。我遇到的問題之一是實體框架不處理字段唯一性。我已經在他們的網站上閱讀了關於Configuring/Mapping Properties and Types with the Fluent API的文章,並且我找不到任何配置將屬性設置爲唯一。

所以,我爲了設置字段的獨特之處是在創建過程中手動運行幾個ALTER SQL語句一樣,

using (MyDBContext _context = new MyDBContext(connString)) 
{ 
    if (_context.Database.CreateIfNotExists()) 
    { 
     _context.Database.ExecuteSqlCommand("ALTER TABLE Account ADD CONSTRAINT UQ_Account_AccountNumber UNIQUE(AccountNumber)"); 
     _context.Database.ExecuteSqlCommand("ALTER TABLE Account ADD CONSTRAINT UQ_Account_GUID UNIQUE(GUID)"); 
     // .... more on this in the following lines ... 
    } 
} 

我的問題:

  1. 我是正確的,實體框架唐沒有任何配置或數據註釋設置字段唯一
  2. 有沒有辦法檢測或知道在EF運行時如果EF創建一個數據庫或不,所以我可以移動或隱藏這個語句if (_context.Database.CreateIfNotExists())某處可用的方法,可以重寫?

我真正想要的是消除從使用statemnt if (_context.Database.CreateIfNotExists())並把它在其他地方或內部MyDBContext所以我的代碼看起來像這樣,

using (MyDBContext _context = new MyDBContext(connString)) 
{ 
    Account _acc = new Account() 
    // ...Account properties ... 

    _context.Account.Add(_acc); 
    _context.SaveChanges(); 
} 

感謝。

+1

如果您不使用EF遷移(您可以在其中定義唯一索引),則可以使用自定義[數據庫初始值設定項](http://stackoverflow.com/questions/5701608/unique-key-with-ef-code -first/5701702#5701702)。 –

回答

1

如果你不使用(或不能使用)EF遷移,你可以使用自定義如this answer中提到的初始化器。當數據庫不存在時,自定義初始化程序將在創建數據庫後僅執行一次Seed方法。如果您需要逐步開發數據庫初始化程序本身不會幫助您(這是遷移的目的)。

+0

這不是我使用Migrations的時候。正如我在聊天中提到的,我正在慢慢理解這一點,並很快遷移到EF遷移。你的答案真的是我正在尋找的。謝謝。 –

4

你應該看看Code First Migrations,更具體的在Data Motion/Custom SQL和後面的章節 - 這可能是實現你想要的結果的方法。遷移類可以是這樣的:

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"); 
    } 
} 

您也可以探索這個問題的答案所描述的其他選項:Unique Constraint in Entity Framework Code First

+0

感謝您的回答,但這不是使用遷移的時間。我正在慢慢採取這些措施。但說實話,這是一個很好的答案':)'+1。 –

相關問題