Entity Framework DataAnnotations

  DataAnnotations由命名空间System.ComponentModel.DataAnnotations提供支持。所以在使用之前,需要先引用该dll。这里列出一些常用的DataAnnotations。

(1)TableAttribute:指定实体类生成的表名

1 [Table("Hotel")]
2 public class Hotel

(2)KeyAttribute:指定主键

1 [Key]
2 public int Id

(3)ColumnAttribute:指定列名、数据类型等

1 [Column("Name", TypeName = "nvarchar")]
2 public string Name { get; set; }

(4)RequiredAttribute:对应的字段不能为null

1 [Required]
2 public string Name { get; set; }

(5)MaxLengthAttribute:对应的字段的最大长度

1 [MaxLength(127)]
2 public string Address {get; set;}

(6)MinLengthAttribute:在数据库中无对应,但是可以约束在代码中的长度

1 [MinLength(10)]
2 public string Name {get; set; }

(7)StringLength:功能包含了MaxLengthAttribute、MinLengthAttribute

1 [StringLength(63, MinimumLength=10)]
2 public string Address {get; set; }

(8)ConcurrencyCheckAttribute:指定用于开放式并发检查的列的数据类型

1 [ConcurrencyCheck]
2 public int Version { get; set; }

(9)TimestampAttribute:将列的数据类型指定为行版本

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

(10)ForeignKeyAttribute:指定导航属性的外键

1 [ForeignKey("ChainId")]
2 public virtual Chain Chain{ get; set; }

(11)DatabaseGeneratedAttribute:指定列的值是由数据库生成的,并指定生成策略(None:数据库不生成值,Identity:当插入行时,数据库生成自增长值,Computed当插入或更新行时,数据库生成值)

1 [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
2 public int Id { get; set; }

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

1 [ComplexType]
2 public class Name
3 {
4     public string FirstName { get; set; }
5     public string LastName { get; set; }
6 } 

(13)NotMappedAttribute:忽略该字段,不做映射

1 [NotMapped]
2 public string IgnoreProperty { get; set; }

 

posted @ 2015-05-07 22:18  lcyan  阅读(122)  评论(0编辑  收藏  举报