EntityFramework Code-First 简易课程(五)-领域类的配置

EntityFramework Code-First 简易教程(五)-------领域类的配置

前言:在前篇中,总是把领域类(Domain Class)翻译成模型类,因为我的理解它就是一个现实对象的抽象模型,不知道对不对。以防止将来可能的歧义,这篇开始还是直接对Domain Class直译。

 

前面我们学习了默认Code-First约定,Code-First使用默认约定根据领域类构建概念模型,Code-First利用一个设计模型参考作为约定来覆盖配置,意思就是我们可以通过配置领域类来覆写这些约定以提供给EF需要的信息,有两种方法配置领域类。

  1. 数据注释(DataAnnotations)
  2. Fluent API

 

数据注释(DataAnnotation):

数据注释是一个简单的配置基础特性,我们可以将其应用在领域类或者领域类的属性上,大多数特性在System.ComponentModel.DataAnnotations命名空间下,但是,数据注释仅仅提供Fluent API配置的一个子集,也就是说如果我们在数据模型中找不到一个特性,那就必须使用Fluent API进行配置了。

下面例子展示了使用了数据注释的Sudent类:

[Table("StudentInfo")]
public class Student
{
    public Student() { }
        
    [Key]
    public int SID { get; set; }

    [Column("Name", TypeName="ntext")]
    [MaxLength(20)]
    public string StudentName { get; set; }

    [NotMapped]
    public int? Age { get; set; }
        
        
    public int StdId { get; set; }

    [ForeignKey("StdId")]
    public virtual Standard Standard { get; set; }
}

 

Fluent API:

Fluent API 配置是作为EF从领域类构建模型的应用,我们可以通过覆写DbContext类的OnModelCreating方法来注入配置,如下代码所示:

public class SchoolDBContext: DbContext 
{
    public SchoolDBContext(): base("SchoolDBConnectionString") 
    {
    }

    public DbSet<Student> Students { get; set; }
    public DbSet<Standard> Standards { get; set; }
    public DbSet<StudentAddress> StudentAddress { get; set; }
        
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        //Configure domain classes using Fluent API here

        base.OnModelCreating(modelBuilder);
    }
}
   

我们也可以使用一个DbModelBuilder类的实例对象来配置领域类

 

后面的文章我们会详细介绍数据注释和Fluent API的使用方法。