Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Entity Framework Code First CTP5, how do I create a primary key column that are INTs and are not identity columns

Using Entity Framework Code First CTP5, how do I create a primary key column that are INTs and are not identity columns

Preferably not using attributes.

like image 927
ajma Avatar asked Feb 15 '11 04:02

ajma


People also ask

How do I set primary key in Entity Framework?

Configuring a primary key By convention, a property named Id or <type name>Id will be configured as the primary key of an entity. Owned entity types use different rules to define keys. You can configure a single property to be the primary key of an entity as follows: Data Annotations.

How does Entity Framework define key?

Key. Entity Framework relies on every entity having a key value that is used for entity tracking. One convention of Code First is implicit key properties; Code First will look for a property named “Id”, or a combination of class name and “Id”, such as “BlogId”.


2 Answers

That answer didn't work for me (in EF 4.1).

To make this work, I added DatabaseGenerated attribute to my key column:

public class FacebookUser {   [Key]   [DatabaseGenerated(DatabaseGeneratedOption.None)]   public long FacebookId { get; set; }    // ... } 

Hope this helps someone.

like image 168
Jay Querido Avatar answered Sep 24 '22 03:09

Jay Querido


If you're building your entities using the fluent interface rather than using attributes over the properties, you may be able to use the DatabaseGenerationOption class (from EntityFramework.dll, in the System.ComponentModel.DataAnnotations namespace). I've not tested it, but this is what it would look like:

modelBuilder     .Entity<Foo>()     .Property(f => f.Id)     .HasDatabaseGeneratedOption(DatabaseGeneratedOption.None); 
like image 33
Matt Hamilton Avatar answered Sep 23 '22 03:09

Matt Hamilton