zoukankan      html  css  js  c++  java
  • Entity Framework Code-First(10):Fluent API

    Fluent API in Code-First:

    We have seen different DataAnnotations attributes in the previous sections to override default Code-First Conventions. Here, we will learn about Fluent API.

    Fluent API is another way to configure your domain classes. Fluent API provides more functionality for configuration than DataAnnotations. Fluent API supports the following types of mappings.

    MappingsTo Database
    Model-wide Mapping
    • Set default Schema
    • Set Custom Convetions
    Entity Mapping
    • To Single or Multiple Tables and Schema
    • To Complex type
    • Inheritance Hierarchies
    Property Mapping
    • To Column, Column Name, Column Type, Nullable or Not Null Column, Column size, Columns Order
    • To Concurrency column
    • To Foreign key column
    • To configure relationships

    Let's get started with Fluent API. First of all, let's create Student & Standard domain classes and context class as we have created in the Simple Code-First Example section. Now, override OnModelCreating method of DBContext in a context class, as shown below.

    public class SchoolContext: DbContext 
    {
        public SchoolDBContext(): base() 
        {
        }
    
        public DbSet<Student> Students { get; set; }
        public DbSet<Standard> Standards { get; set; }
            
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            //Configure domain classes using modelBuilder here
    
            base.OnModelCreating(modelBuilder);
        }
    }

    Now, all your configuration code using Fluent API should be in OnModelCreating method. DbModelBuilder is a main class on which you can configure all your domain classes because at this point, all your domain classes would have initialized.

    You can also use DataAnnotation and Fluent API at the same time. Code-First gives precedence to Fluent API > data annotations > default conventions.

    DbModelBuilder class includes important properties and methods to configure. Visit MSDN for more information on DbModelBulder class.

    Let's start to configure entities using Fluent API in the next section.

  • 相关阅读:
    LINQ 为C#开发的一种类似于SQL的语言
    Perl函数集
    职场新鲜人:为什么女生拼不过男生?
    字符串查找 cmd find命令
    职业规划师:如何给自己挑选一个好老板
    C# const, readonly, static readonly
    转载:抽象工厂模式与工厂方法模式区别
    教育法则
    poj 1509 Glass Beads
    hdu 2602 Bone Collector
  • 原文地址:https://www.cnblogs.com/purplefox2008/p/5644231.html
Copyright © 2011-2022 走看看