Using code first, disable identity (auto-incrementing) on integer primary key.

asp.net-mvc-3 entity-framework

Question

I am using code first approach in a ASP.NET MVC 3 application and all integer primary keys in models (public int Id { get; set; }) are by default configured as an identity with auto-incrementing. How to disable this and enable a way to manually enter the integer for the primary key?

The actual situation is that the Id integers have a special meaning and I would therefore like to have them choosable at creation and later editable. It would be ideal if in case the integer is not given at creation time it is auto-incremented, else the specified value is used. But editable primary fields is my primary need. Is there any way to do this elegantly in ASP.NET MVC 3?

1
41
9/18/2012 3:57:21 PM

Accepted Answer

Use these data annotation options:

  • [System.ComponentModel.DataAnnotations.KeyAttribute()]
  • [System.ComponentModel.DataAnnotations.DatabaseGenerated(System.ComponentModel.DataAnnotations.DatabaseGeneratedOption.None)]
55
11/24/2011 4:47:30 PM

Popular Answer

You can use FluentMapping:

modelBuilder.Entity<*entityname*>().Property(m => m.*fieldname*)
             .HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow