zoukankan      html  css  js  c++  java
  • 【CodeFirst 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 的更详细的介绍。

  • 相关阅读:
    欧拉公式
    isap的一些想法
    错误合集
    Hello World
    PAT (Advanced Level) Practice 1068 Find More Coins
    PAT (Advanced Level) 1087 All Roads Lead to Rome
    PAT (Advanced Level) 1075 PAT Judge
    PAT (Advanced Level) 1067 Sort with Swap(0, i)
    PAT (Advanced Level) 1017 Queueing at Bank
    PAT (Advanced Level) 1025 PAT Ranking
  • 原文地址:https://www.cnblogs.com/ztpark/p/6830569.html
Copyright © 2011-2022 走看看