Fluent API

From Logic Wiki
Jump to: navigation, search


Fluent API supports following types of mappings.

  • 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

Fluent API configuration is applied as EF builds the model from your domain classes You can inject the configurations by overriding the DbContext class's 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.

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