2

I need to set the sql server columns "default value or binding" OnModelCreating (or as an property attribute) in EF code first. The reason is that I want to use sql 2012 sequence instead of autogenerated identity.

To use a sequence in sql 2012 i need to achive this:

SQL 2012 sequence

How can this be done with entity framework 4.3 Code first?

Danny Varod
  • 17,324
  • 5
  • 69
  • 111
stian.net
  • 3,928
  • 4
  • 25
  • 38
  • I have provided the answer here using a custom attribute: http://stackoverflow.com/questions/19554050/entity-framework-6-code-first-default-value/34894274#34894274 – ravinsp Jan 26 '16 at 14:47

2 Answers2

2

I think this isn't supported yet for entity framework CodeFirst so default value can be set only with the help of XML mapping (EDMX).

You can vote here for new features: http://data.uservoice.com/forums/72025-ado-net-entity-framework-ef-feature-suggestions/suggestions/2541076-allow-using-sql-server-2012-sequence-for-generatin

As much as i know FluentAPI enables you to use DatabaseGeneratedOption http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.databasegeneratedoption(v=vs.103).aspx

protected override void OnModelCreating(DbModelBuilder modelBuilder)  
{
   modelBuilder.Entity<YourEntity>().Property(p => p.YourColumn)  
          .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity) //None,Identity,Computed

}
Matija Grcic
  • 12,963
  • 6
  • 62
  • 90
0

I know this is an old question but may help someone looking for this answer in EF 6. You can accomplish this using migrations:

public override void Up()
{
    AlterColumn("dbo.table_name", "FieldName", c => c.Guid(defaultValueSql: "YOU_SQL_FUNCTION_HERE", nullable: false));
}
Bruno Farias
  • 785
  • 8
  • 22