Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework Code First Using One column as Primary Key and another as Auto Increment Column

I have a class named Sale

public class Sale {     public int Id { get; set; }     public string TrNo { get; set; }     public DateTime Date { get; set; }     public int CustomerID { get; set; }      public ObservableCollection<SaleDetail> SaleDetails { get; set; } } 

And in the database, I want the Id as the Auto Increment column and the TrNo as the Primary Key column.

Please tell me how to do this using EF5 code first.

Thanks.

like image 946
Seevali H Rathnayake Avatar asked Jan 30 '13 20:01

Seevali H Rathnayake


People also ask

Can auto increment be a primary key?

Auto-increment allows a unique number to be generated automatically when a new record is inserted into a table. Often this is the primary key field that we would like to be created automatically every time a new record is inserted.

Can I auto increment a column that is not a primary key?

There can be only one AUTO_INCREMENT column per table, it must be indexed, and it cannot have a DEFAULT value. So you can indeed have an AUTO_INCREMENT column in a table that is not the primary key.


2 Answers

You can also do this with Data Annotations:

public class Sale {     [DatabaseGenerated(DatabaseGeneratedOption.Identity)]     public int Id { get; set; }      [Key]     public string TrNo { get; set; }      public DateTime Date { get; set; }     public int CustomerID { get; set; }      public ObservableCollection<SaleDetail> SaleDetails { get; set; } } 
like image 141
Corey Adler Avatar answered Sep 18 '22 15:09

Corey Adler


I believe you can do this using Fluent API

protected override void OnModelCreating(DbModelBuilder modelBuilder) {     modelBuilder.Entity<Sale>().Property(a => a.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);     modelBuilder.Entity<Sale>().Property(a => a.TrNo).HasKey(b => b.TrNo); } 
like image 24
Jake Avatar answered Sep 21 '22 15:09

Jake