【Code-First Tutorial】 配置域类(Configure Domain Classes)

查看原文

有两种配置域类的方式:

 

一、数据标注(DataAnnotation

数据标注是一种基于配置的简单特性。这些特性,大部分在 System.ComponentModel.DataAnnotations 命名空间下。然而,数据标注只提供 Fluent API 配置的一个子集。,所以,如果你在数据标注中找不到的一些特性,就要使用  Fluent API 来配置。

以下是一个数据标注的例子:

[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 类的一个对象 modelBuilder,来配置域类。

 

在下一章中,我们将看到关于数据标注和 Fluent API 的更详细的介绍。

 

posted @ 2017-05-09 14:49  ztpark  阅读(136)  评论(0编辑  收藏  举报