我是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 ...
}
}
我的問題:
- 我是正確的,實體框架唐沒有任何配置或數據註釋到設置字段唯一?
- 有沒有辦法檢測或知道在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();
}
感謝。
如果您不使用EF遷移(您可以在其中定義唯一索引),則可以使用自定義[數據庫初始值設定項](http://stackoverflow.com/questions/5701608/unique-key-with-ef-code -first/5701702#5701702)。 –