• Entity Framework Code-First(8):Configure Domain Classes


    Configure Domain Classes in Code-First:

    We learned default Code-First Conventions in the previous section. Code-First builds conceptual model from your domain classes using default conventions. Code-First leverages a programming pattern referred to as convention over configuration. It means you can override these conventions by configuring your domain classes to provide EF with the information it needs. There are two ways to configure your domain classes.

    1. DataAnnotations
    2. Fluent API

    DataAnnotation:

    DataAnnotation is a simple attribute based configuration, which you can apply to your domain classes and its properties. You can find most of the attributes in theSystem.ComponentModel.DataAnnotations namespace. However, DataAnnotation provides only a subset of Fluent API configurations. So, if you don't find some attributes in DataAnnotation, then you have to use Fluent API to configure it.

    Following is an example of DataAnnotation used in Student Class:

    [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 configuration is applied as EF builds the model from your domain classes You can inject the configurations by overriding the DbContext class' OnModelCreating method as following:

    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);
        }
    }

    You can use modelBuilder, which is an object of DbModelBuilder class, to configure domain classes.

    Let's see DataAnnotation and Fluent API in detail in the next chapter.

  • 相关阅读:
    JQuery图片预览
    1.数组
    1.什么是C++
    安装PHPCMS 遇到的问题(fsockpen)
    解决采集时提示”没有找到网址列表,请先进行网址采集“的问题
    JAVA 常用的网站
    页面静态化
    我的C笔记系列一
    PHP缓存技术
    PHPCMS 采集规则
  • 原文地址:https://www.cnblogs.com/purplefox2008/p/5644087.html
Copyright © 2020-2023  润新知