c# - Generate Guid on database but only when not set in entity -


i have case need add guid property not primary key, , shared several objects in table.

what i'd is:

  • generate guid on database when don't give value
  • set guid (instead of generating it) when have value

both of done on insert only, updates won't touch these values.

what have tried:

  • add [databasegenerated(databasegeneratedoption.identity)] attribute: works when don't need set guid manually
  • add [databasegenerated(databasegeneratedoption.computed)] attribute: doesn't work when don't set guid manually

i've seen quite lot topic, , closest thing article: http://www.davepaquette.com/archive/2012/09/23/calculated-columns-in-entity-framework-code-first-migrations.aspx

but don't (and won't) use migration in our project, doesn't seem fit.

or question, mean generating guids in .net (which doesn't seem clean, @ least in opinion): ef, code first - how set custom guid identity value on insert

is there way generate guid database side, , set when need in ef code first?

if not, alternative? bad idea generate guids on .net side? (i go if nothing else possible)

i assume using ms-sql , can following

to use execute command

public class yourdbcontext: dbcontext {      public yourdbcontext():base("connectionstring")      {                           if (database.exists())             {                                    database.executesqlcommand("if object_id('ct_defaultguid') null alter table yourtable add constraint ct_defaultguid default newid() yourcolumn");             }      } } 

to set id .net, can following

  • create base entity contains id property
  • in constructor check if id empty initialize
  • let entities have inherits class

your base class should like

public class baseentity {      public baseentity()      {           if(id==guid.empty)                id = guid.newguid();      }       public guid id{get;set;} } 

to use migration existing database

  • from pmc => enable-migrations
  • from pmc => add-migration "firstrun"
  • open generated migration file , make sure empty up , down methods ( not apply changes on database)
  • add corresponding alter column fluent code using sql("") method in method
  • from pmc => update-database -script , make sure sql statement generated alter table statement
  • from pmc => once sure desired statement appearing in sql script , apply : update-database.

your class should this

public class firstrun : dbmigration {    public override void up()      {         sql("alter table yourtable add constraint ct_defaultguid default newid() yourcolumn");      } } 

i recommend last approach, executed once, , can add changes later database.

hope you


Comments

Popular posts from this blog

unity3d - Rotate an object to face an opposite direction -

angular - Is it possible to get native element for formControl? -

javascript - Why jQuery Select box change event is now working? -