Entity Framework Code-First(9.1):DataAnnotations - Key Attribute
2016-07-05 16:25
435 查看
DataAnnotations - Key Attribute:
Key attribute can be applied to properties of a class. Default Code-First convention creates a primary key column for a property whose name is "Id" or {Class Name} + "Id". Key attribute overrides this default convention. You can apply Key attribute to a property with any name, which you want to create a primary key for.Consider the following example.
using System.ComponentModel.DataAnnotations; public class Student { public Student() { } [Key] public int StudentKey { get; set; } public string StudentName { get; set; } }
As you can see in the above example, Key attribute is applied to StudentKey property of the Student class. So, Code First will override default conventions and create a primary key column StudentKey in the Student table as shown below.
You can also create a composite primary key and make two columns as PK using Key attribute and Column attribute as shown below.
using System.ComponentModel.DataAnnotations; public class Student { public Student() { } [Key] [Column(Order=1)] public int StudentKey1 { get; set; } [Key] [Column(Order=2)] public int StudentKey2 { get; set; } public string StudentName { get; set; } }
The above code creates composite primary key columns StudentKey1 and StudentKey2 in Student table as shown below.
Note: Key attribute creates a PK with identity column when applied to a single integer type property. Composite key does not create an identity column for integer property. Also, Key attribute can be applied to a property of any data type except unsinged integers, e.g. string, datetime, decimal etc.
相关文章推荐
- Spring依赖注入:注解注入总结
- 更新用blob字段存储照片的Java代码
- 一个女孩数次被车撞的经历
- ld Memory exhausted一解
- PHP正则表达式学习笔记
- easyui学习(1)
- zimbra安装
- C#中Main()和四种参数类型
- .net 反射实现两个相同结构实体类的转换
- Java线程的5种状态及切换
- KK GMS无法通过网络定位
- kafka connect 数据写hdfs详解
- Redis 基本命令备忘
- Android集成微信支付
- Portal认证方式
- HTML5实例教程:OL标签的start属性和reversed属性
- JavaScript 作用域 理解
- Java设计模式 -- 策略模式
- 在Struts2 中 ValueStack 的实现(一)
- 在Xcode中安装插件来完成真实文件夹的创建&插件管理工具的安装