Entity Framework DataAnnotations

时间:2023-03-09 22:45:26
Entity Framework DataAnnotations

前言

DataAnnotation 特性由.NET 3.5中引进,给.NET中的类提供了一种添加验证的方式。但是在EF中它又可以对映射关系进行控制,相比较Fluent API使用起来要简单一些。

DataAnnotation特性列举

DataAnnotation由命名空间System.ComponentModel.DataAnnotations提供。下面列举实体模型中常用的DataAnnotation特性:

1.KeyAttribute:对数据库中表的主键的设置

        [Key]
public int OrderID { get; set; }

2.RequiredAttribute:对应数据库中字段的数据是否可以为null

        [Required]
public string OrderName { get; set; }

3.MaxLengthAttribute:对应数据库中字符串类型字段的最大长度

        [MaxLength(60)]
public string Employee{get;set;}

4.MinLengthAttribute:在数据库中无对应,但在代码中字符串最小长度

        [MaxLength(60),MinLength(10)]
public string Employee{get;set;}

5.ConcurrencyCheckAttribute:指定用于开放式并发检查的列的数据类型

        [ConcurrencyCheck]
public string Address { get; set; }

6.TimestampAttribute:将列的数据类型指定为行版本

        [Timestamp]
public byte[] TimeStamp { get; set; }

System.ComponentModel.DataAnnotations命名空间中只定义了部分实体验证的特性,在EntityFramework程序集中定义了更多的数据映射特性

7.DatabaseGeneratedAttribute:标记指定实体属性是由数据库生成的,并指定生成策略(None数据库不生成值,Identity当插入行时,数据库生成值,Computed当插入或更新行时,数据库生成值)

        [DatabaseGenerated(DatabaseGeneratedOption.Computed)]
public DateTime CreateDate { get; set; }

8.ColumnAttribute:指定实体属性在数据库中的列名及数据类型

        [Column("Notes", TypeName = "ntext")]
public string Note { get; set; }

9.TableAttribute:指定实体类对应的数据表名

    [Table("Order",Schema="Order")]
public class Order

10.ForeignKeyAttribute:指定导航属性的外键字段

    public class Customer
{
public int ID { get; set; } public string Name { get; set; }
}
[ForeignKey("ID")]
public Customer customer { get; set; }

11.NotMappedAttribute:标记指定实体属性在创建数据库中不创建对应字段

        [NotMapped]
public string PhotoPath { get; set; }

12.ComplexTypeAttribute:标记指定实体属性是将一个对象作为另一个对象的属性,映射到数据库中则子对象表现为多个属性字段

[ComplexType]
public class Name
{
public string FirstName { get; set; } public string LastName { get; set; }
}
public Name Name { get; set; }

对于实体关系对应的数据表关系,无非“0:1,1:1,0:N,1:N,N:N”这几种,可以使用导航属性中的数据类型来表示,0…1端使用单实体类型表 示,N端使ICollection<T>集合类型表示。对于单实体端,默认是可为空的,即为0关系,如果要设置为1关系,要使用 [Required]标签来进行标记。但对于一对一中的关系主体与依赖对象确无法做更细节的控制。

注意:DataAnnotations可以同时在同一个类后者属性上使用多个标记属性,上面的例子中对于每个类或属性只使用了一个单独的标记属性是为了说明起来更加简单;另外声明的例子中同时使用“ConcurrencyCheck”和“TimeStamp”指定了不同的列只是为了演示,一般情况下我们通过其中一种方式即可。