Search code examples
asp.netentity-frameworkasp.net-mvc-4ef-fluent-apief-model-builder

Unable to find the code generated by Fluent API model builder mapping in the Database Context


I am working with ASP.NET MVC 5 with Entity Framework 6.

I adjusted my achiteture by moving my models to a separate data project in an attempt to follow Clean Architecture.

Normally when I have all the models in the same project and the database context with it, entity framework generates mappings in the context to reflect the relationships that were indicated by how I defined the models( using public virtual ICollection... etc).

Example of the code from database context when models are all in one project is shown below:

 protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
        //many to many Company-Services
        modelBuilder.Entity<Company>()
         .HasMany(s => s.Services)
         .WithMany(c => c.Company)
         .Map(cs =>
         {
             cs.MapLeftKey("CompanyRefId");
             cs.MapRightKey("ServiceRefId");
             cs.ToTable("CompanyServices");
         });

        //Staff-Qualifications
        modelBuilder.Entity<Staff>()
         .HasMany(q => q.Qualifications)
         .WithMany(s => s.Staff)
         .Map(cs =>
         {
             cs.MapLeftKey("StaffRefId");
             cs.MapRightKey("QualificationRefId");
             cs.ToTable("StaffQualifications");
         });
    }

However now that I have the models in a separate data project in the same solution, the database context has none of this code anymore. It just has this simple Fluent API code that I included below.

Code that is in the context when the models are in a separate project in the same solution:

            protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
    }

Upon examination in server management studio, the tables are generated the same way in the database as if the model builder code was there.

I found this alarming and was wondering how the tables and their relationships were still generated correctly without the Fluent API. I searched the project for the model builder code but could not find it anywhere.

Is the absence of this Fluent API code a problem or a potential problem? Anyone know how this works if it seemingly does not need this code to make the database relationships ?


Solution

  • Database mapping is by convention, customizable with Attribute-based configuration or the Fluent API. See Code-First Conventions

    So even without any explicit configuration, EF can generate the database.