Seevali Seevali - 24 days ago 6
C# Question

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.

Answer

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.

Comments