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


i new entity framework 5. our team using code first workflow.

before i'll start main question, let me first show have tried (the ultimate comment of time :d).

public class mydbcontext : cdbcontext {     public mydbcontext() : base(connstring) { }      public mydbcontext(string connstr) : base(connstr) { }      protected override void onmodelcreating(dbmodelbuilder modelbuilder)     {         // removes conventions         modelbuilder.conventions.remove<manytomanycascadedeleteconvention>();         // ........          // model configurations contains mappings         modelbuilder.configurations.add(new accountconfiguration());         // ........          // calls base onmodelcreating         base.onmodelcreating(modelbuilder);     }      // list of entity     public dbset<account> account { get; set; } } 

mydbcontext class have created inherits cbdcontext contains override methods , inherits dbcontext. 1 of problems have encountered entity framework doesn't handle field uniqueness. have read article on configuring/mapping properties , types fluent api on site , can't find configuration set property unique.

so did in order set field unique manually run several alter sql statements during creation,

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 in following lines ...     } } 

my questions:

  1. am right entity framework don't have configuration or data annotations set field unique?
  2. is there way detect or know during runtime if ef creates database or not can move or hide statement if (_context.database.createifnotexists()) somewhere available method can overriden?

what want remove if (_context.database.createifnotexists()) using statemnt , put somewhere else or inside mydbcontext code this,

using (mydbcontext _context = new mydbcontext(connstring)) {     account _acc = new account()     // ...account properties ...      _context.account.add(_acc);     _context.savechanges(); } 

thanks.

if don't use (or cannot use) ef migrations can use custom initializer mentioned in this answer. custom initializer execute seed method after creating database = once when database doesn't exist. if need incrementally develop database initializer not (that migrations for).


Comments

Popular posts from this blog

Why does Ruby on Rails generate add a blank line to the end of a file? -

keyboard - Smiles and long press feature in Android -

node.js - Bad Request - node js ajax post -