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.
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.
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.
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; } }
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); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With