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”指定了不同的列只是為了演示,一般情況下我們通過其中一種方式即可。 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM