Code First 约定
Code First 约定
Code First 使开发者可以用一个C#或者VB的类来描述一个model,model的基本特性根据约定进行检测。约定是一组可以根据C#或者VB的类定义生产概念模型的规则。这些约定位于System.Data.Entity.ModelConfiguration.Conventions命名空间下。
开发者也可以用data annotations 或the fluent API来配置生产自己的模型。配置优先权按照 fluent API,data annotations ,conventions的顺序。
Code First 的详细信息在API Documentation中可以找到。本文可以让开发者略览Code First约定。
Type Discovery
使用代码首先发展时,开发者一般先写作定义“概念模型”的.NET Framework类。要对定义好的.NET Framework类进行改动,你需要让DbContext知道你想在模型中添加什么类型。想实现这步,你需要定义一个继承DbContext的context class,并公开一个你想要包含在模型中的DbSet属性。Code First 将包含这些类型,也可以驱动任何引用类型,即便这些引用类型在完全不同的assembly中。
如果你的类型中存在继承关系,你只需为基类定义DbSet属性,继承类将自动包含这些属性。
在下面的例子中, SchoolEntities class 只有一个DbSet属性(Departments)。 Code First 用这个属性来发现和检测引用类型。
1 public class SchoolEntities : DbContext 2 { 3 public DbSet<Department> Departments { get; set; } 4 } 5 6 public class Department 7 { 8 // Primary key 9 public int DepartmentID { get; set; } 10 public string Name { get; set; } 11 12 // Navigation property 13 public virtual ICollection<Course> Courses { get; set; } 14 } 15 16 public class Course 17 { 18 // Primary key 19 public int CourseID { get; set; } 20 21 public string Title { get; set; } 22 public int Credits { get; set; } 23 24 // Foreign key 25 public int DepartmentID { get; set; } 26 27 // Navigation properties 28 public virtual Department Department { get; set; } 29 } 30 31 public partial class OnlineCourse : Course 32 { 33 public string URL { get; set; } 34 } 35 36 public partial class OnsiteCourse : Course 37 { 38 public string Location { get; set; } 39 public string Days { get; set; } 40 public System.DateTime Time { get; set; } 41 }
如果你想从模型中排除类型,使用NotMapped属性或DbModelBuilder.Ignore fluent API。
modelBuilder.Ignore<Department>();
Primary Key Convention
Code First 根据属性名是否为"ID"或者以"ID"结尾来推断是否为主键。如果主键属性的类型是numeric或GUID,该列将被配置为一个标识列。
1 public class Department 2 { 3 // Primary key 4 public int DepartmentID { get; set; } 5 6 . . . 7 8 }
Relationship Convention
未完。。。