MVC 5:代码优先方法 - 主键 [英] MVC 5: Code First Approach - Primary Key

查看:69
本文介绍了MVC 5:代码优先方法 - 主键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

public class ExpenseModel
{
   public int id { get; set; }
   public string reason { get; set; }
   public decimal price { get; set; }
   public DateTime dtCreated { get; set; }
}





我写了一个模特。



实体框架(EF)Code First模型将创建一个数据库和表,其中'id'为主键。



我的问题是

1.如何EF决定'id'将成为主键?

2.如果想将另一列设置为主键,写什么?

3.我如何设置复合键?

4.如何将主键设置为自动增量?



所有上述问题都与EF Code First模型相同



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

推荐答案

答案#1。



实体框架将推断因为该属性被称为Id。



答案#2。



使用[key]注释



ANSWER #1.

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

ANSWER #2.

Use the [key] annotation

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





答案#3。



以下是如何获得复合键





ANSWER #3.

Below is how you get a composite Key

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; }
}





答案#4。







ANSWER #4.


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; }
}


这篇关于MVC 5:代码优先方法 - 主键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆