Monday, February 5, 2018

Database First Approach

This is another way of creating model classes and work with them. In this workflow model, it supports:

  • Creates Model / POCO objects from an existing database and these will become the link between the database and controller(s)
  • It uses the model/database sync, code generation, in the same way as we used in the Model First approach
  • This is an alternative approach provided by Entity Framework besides Code First and Model First approaches









Database First approach is recommended when:
  • Working with stable databases schemas
  • Changes to database and models are incremental
  • When you have a database designed separately by DBAs or if you have existing database
Advantages
  • Useful when the database is already existing
  • Simple to create the data model using existing database objects
  • Mapping and creation of keys and relationships are automatically handled by EF and no need to write any code
  • Usually preferred for intense data and large applications
  • Easy to avoid data loss on changes as you wlll work from database perspective
  • Query performance and better integrated with Stored Procedures and Functions
Disadvantages
  • Giant pile of auto generated code when working with an huge database to generate EDMX
  • Always needs to extend the auto generated classes to extend the functionality
  • Creating associations, foreign keys, constraints etc. from the database can be more difficult
  • Not easy to sync database changes made locally
  • Sometimes handling edmx with version controlling is challenge
  • Database deployment is a painful process
  • Going forward EF will not support EDMX based modeling
Steps to implement Database First approach
  • Create a new ASP.NET MVC or Web API project
  • Using Manage Nuget Packages option install latest Entity Framework
  • Update web.config with connection string
  • Generate Model(s) by
    • Data -> ADO.NET Entity Data Model
    • Then pick "EF Designer" from Database
    • Pick newly created context from web.config as new context class name
    • Select needed SQL objects like Tables, Views and Stored Procedures
    • Once clicking on Ok, Models and .edmx will be generated after theses steps
  • Updating .edmx can be done by
    • Make required changes using SSMS
    • From .edmx, right click and pick "Update Model from Database" option
  • Fluent API will go hand to hand to create relationships like one-to-zeroorone, one-to-many and many-to-many etc.

No comments:

Post a Comment