【译】第8节---EF Code First中配置类

原文:http://www.entityframeworktutorial.net/code-first/configure-classes-in-code-first.aspx

前面的章节中我们知道, Code-First使用默认约定从您的域类构建概念模型。Code First利用一种称为【约定大于配置】的编程模式。这意味着您可以通过配置域类来为EF提供所需的信息来覆盖这些约定。

有两种配置域类的方法:

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

DataAnnotation(数据注解)

DataAnnotation是一个简单的基于属性的配置,您可以将其应用于您的域类及其属性。您可以在System.ComponentModel.DataAnnotations命名空间中找到大部分属性。但是,DataAnnotation仅提供Fluent API配置的一个子集。

因此,如果在DataAnnotation中找不到某些属性,则必须使用Fluent API进行配置。

下面是在学生类中使用的DataAnnotation的示例:

[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来配置域类。

后面的章节将详细介绍DataAnnotation和Fluent API。

原文地址:https://www.cnblogs.com/talentzemin/p/7193927.html