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

Topics: EF Designer, EF Power Tools, EF Runtime, General
Jan 31, 2013 at 5:50 PM
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. (I'm using MySQL as the DB)

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

Thanks.
Developer
Jan 31, 2013 at 7:51 PM
Edited Jan 31, 2013 at 7:52 PM
Hi seevali,

To specify the primary key you can either put the KeyAttribute data annotation on the TrNo property, or use the EntityTypeConfiguration.HasKey fluent API method in OnModelCreating.

E.g. modelBuilder.Entity<Sale>().HasKey(s => s.TrNo);

Likewise, to make Id auto-incrementing you can either put the DatabaseGeneratedAttribute data annotation on the property, or use the PrimitivePropertyConfiguration.HasDatabaseGeneratedOption fluent API method in OnModelCreating.

Cheers,

Andrew