博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Entity Framework Code-First(9.1):DataAnnotations - Key Attribute
阅读量:6153 次
发布时间:2019-06-21

本文共 1739 字,大约阅读时间需要 5 分钟。

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.

转载于:https://www.cnblogs.com/purplefox2008/p/5644102.html

你可能感兴趣的文章
在Linux切割文件
查看>>
进度总结
查看>>
软件测试2019:第八次作业
查看>>
MySQL 基础 之 语句执行顺序
查看>>
Codeforces Goodbye 2018
查看>>
Asp.net页面间传值方式汇总
查看>>
C# 数组、ArrayList和List三者的区别
查看>>
docker的核心原理-cgroup
查看>>
浅析操作系统函数调用原理-附实例
查看>>
直线恒过定点问题
查看>>
Elasticsearch初级语句入门
查看>>
洛谷P4762 [CERC2014]Virus synthesis(回文自动机+dp)
查看>>
利用PIL和Selenium实现页面元素截图
查看>>
cdoj 树上战争(Battle on the tree) Label:并查集?
查看>>
LightOJ 1236 Pairs Forming LCM(LCM为n的数对个数)
查看>>
快速排序算法 JDK6 和JDK 7
查看>>
原生态Ajax(转)
查看>>
页面间对象传递的方法
查看>>
解决Ajax跨域问题:Origin xx is not allowed by Access-Control-Allow-Origin.
查看>>
js闭包
查看>>