EF CodeFirst数据注解特性详解

数据注解特性是.NET特性,可以在EF或者EF Core中,应用于实体类上或者属性上,以重写默认的约定规则。

在EF 6和EF Core中,数据注解特性包含在System.ComponentModel.DataAnnotations命名空间和System.ComponentModel.DataAnnotations.Schema命名空间下。

这些特性不仅仅适用于EF,同样适用于ASP.NET MVC以及数据控件。

System.ComponentModel.DataAnnotations.Schema Attributes

[Table(string name,[Schema = string])]

name 想要定义的表名称

Schema 可选参数,数据库的模式名称

[Column(string name,[Order = int],[TypeName = string])]

name 列名

Order 可选参数,列的顺序,从0开始,注意必须为每个属性都设置(不可重复)才能生效、

TypeName 可选参数,列的数据类型

[NotMapped]  不将该属性映射到数据库的列

[ForeignKey(string name)]  设置外键3种方式

[Index(string name)] 为列创建索引

IsClustered用来创建聚合索引, IsUnique用来创建唯一索引。

[InverseProperty(string name)]  有多个对应关系时,指定关系

 

System.ComponentModel.DataAnnotations Attributes

[Key]  设为主键(EF Core中不能使用)

[Required]  设置列不为空

[MaxLength(int)]  设置最大长度,只能用在string类型和byte[]数组类型

猜你喜欢

转载自www.cnblogs.com/1016391912pm/p/12047207.html