Tuesday, December 10, 2013

Fluent API in Code-First

As you have seen in previous chapter that you can configure your domain classes by overriding OnModelCreating method of DBContext in your context class. For example:
    
    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 is main class by which you can configure domain classes. Configuration done by using the DbModelBuilder API takes precedence over data annotations which in turn take precedence over the default conventions.

DbModelBuilder class has following important property and method:
Property / Method NameDescriptionReturn Type
ConventionsProvides access to the settings of this DbModelBuilder that deal with conventions. You can disable the conventions for the DbModelBuilder. 
Entity<TEntityType>()Registers an entity type as part of the model and returns an object that can be used to configure the entity. This method can be called multiple times for the same entity to perform multiple lines of configuration.EntityTypeConfiguration<TEntityType>

Visit MSDN for more information on DbModelBulder class.

No comments:

Post a Comment