Click here to Skip to main content
15,887,866 members
Please Sign up or sign in to vote.
3.00/5 (1 vote)
C#
public class ExpenseModel
{
   public int id { get; set; }
   public string reason { get; set; }
   public decimal price { get; set; }
   public DateTime dtCreated { get; set; }
}


I have written a model.

The Entity Framework(EF) Code First model will create a database and table with 'id' as primary key.

My questions are
1.how EF decided that 'id' will be primary key?
2.What to write if want to set another column as primary key?
3.How can i set composite key?
4.How can i set a primary key as an auto-increment?

All the above questions are w.r.t to EF Code First model
Posted

1 solution

ANSWER #1.

Entity Framework will infer that because the property is called Id.

ANSWER #2.

Use the [key] annotation

C#
public class ExpenseModel
{
   [KEY]
   public int id { get; set; }
   public string reason { get; set; }
   public decimal price { get; set; }
   public DateTime dtCreated { get; set; }
}


ANSWER #3.

Below is how you get a composite Key

C#
public class ExpenseModel
{
   [Key, Column(Order = 0)]
   public int id { get; set; }
   [Key, Column(Order = 1)]
   public string reason { get; set; }
   public decimal price { get; set; }
   public DateTime dtCreated { get; set; }
}


ANSWER #4.


C#
public class ExpenseModel
{
   [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
   public int id { get; set; }
   public string reason { get; set; }
   public decimal price { get; set; }
   public DateTime dtCreated { get; set; }
}
 
Share this answer
 
Comments
[no name] 10-May-16 7:25am    
Very Nice Explain Sir. I'm impressed

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900