CodeFirst编程之字段定义
1、命名空间
在默认约定的情况下,Entity Framework Code First创建的表名是根据类名的英语复数形式,创建的表所有者为dbo,可以通过重写约定来指定表名及表的所有者;
在使用Data Annotation方式进行Entity Framework Code First与数据库映射之前,需要先添加命名空间引用;
1 using System.ComponentModel.DataAnnotations.Schema;
为类配置对应表名并指定表的所有者:
1 [Table("Product", Schema = "dbo")] 2 public class Product
在使用Required特性(Attribute)设置字段不允许为空时,需要添加命名空间引用:
1 using System.ComponentModel.DataAnnotations;
1 [Column("ProductID")] 2 public int ProductID { get; set; } 3 4 [MaxLength(100)] 5 [Required, Column("ProductName")] 6 public string ProductName { get; set; }
3、主键
Entity Framework Code First对于int类型的主键,会自动的设置其为自动增长列。但有时我们确实不需是自动增长的,可以通过以下方式进行取消自动增长。
Data Annotation方式:
取消自动增长
1 [Key] 2 [Column("ProductID")] 3 [DatabaseGenerated(DatabaseGeneratedOption.None)] 4 public int ProductID { get; set; }
自动增长
1 [Key] 2 [Column("CategoryID")] 3 [DatabaseGenerated(DatabaseGeneratedOption.Identity)] 4 public int CategoryID { get; set; }
2、数据类型