29

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.

  • Something like this: http://stackoverflow.com/questions/12012736/entity-framework-code-first-using-guid-as-identity-with-another-identity-column – Jordy Langen Jan 30 '13 at 20:22
  • Why do you need Id column, if TrackingNumber is a good, natural identifier? – krzychu Aug 19 '14 at 07:06
  • @Seevali do you resolved this ? i has the same issue please provide solution – Neo Nov 08 '15 at 04:29

4 Answers4

48

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; }
}
Corey Adler
  • 15,897
  • 18
  • 66
  • 80
17

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);
}
Jake
  • 733
  • 8
  • 23
7

Apparently the answer of @IronMan84 correct. But it didn't work for me. I slightly modified it to apply my another condition. And it worked. I did nothing else.

This is my solution.

public class Sale
{
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }

    [Key, Column(TypeName = "varchar"), MaxLength(50)]
    public string TrNo { get; set; }

    public DateTime Date { get; set; }
    public int CustomerID { get; set; }

    public ObservableCollection<SaleDetail> SaleDetails { get; set; }
}

Unfortunately I can't make the answer of @IronMan84 as the correct one as it didn't work for me.

Community
  • 1
  • 1
4

This helped me. Hope this helps anyone else that still looking around

public class Sale
    {
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]//switch on autogenerated
        public int Id { get; set; }

        [Key]//set as Primary key
        [DatabaseGenerated(DatabaseGeneratedOption.None)]// switch off autogenerated PK
        public string TrNo { get; set; }

        public DateTime Date { get; set; }
        public int CustomerID { get; set; }

        public ObservableCollection<SaleDetail> SaleDetails { get; set; }
}
Jephren Naicker
  • 336
  • 1
  • 2
  • 18