csharppulse.blogspot.in-learning_mvc_part_4__creating_mvc_application_with_entityframework_code_first_approach.pdf...

Upload: zoranmatusko

Post on 01-Jun-2018

221 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/9/2019 csharppulse.blogspot.in-Learning_MVC_Part_4__Creating_MVC_Application_with_EntityFramework_Code_First_Approac

    http:///reader/full/csharppulseblogspotin-learningmvcpart4creatingmvcapplicationwithentityframeworkcodefirstappr 1/8

    csharppulse.blogspot.in http://csharppulse.blogspot.in/2013/09/learning-mvc-part-4-creating-mvc.html

    Learning MVC Part 4 : Creating MVC Application with

    EntityFramework Code First Approach

    Download Complete Source Code

    Introduction

    In our first three articles, we learnt a lot about MVC, starting from definition to use, from creating an application to

    connecting the MVC application with database using different techniques.

    In the very last part of the series, we learnt how to connect our MVC application with existing database using

    Entity Framework.

    This article will focus on connecting our MVC application with database using CodeFirst approach, i.e., one of the

    features Microsofts Entity Framework provides.

    Our Roadmap

    Just to remind our full roadmap towards learning MVC:

    1. Part1: Introduction to MVCarchitecture and Separation of Concerns.

    2. Part 2: Creating MVC Application fromscratch and connecting it with database using LINQ to SQL.

    3. Part 3: Connecting the MVC Application with the help of EntityFramework DB-First approach.

    4. Part 4: Connecting the MVC Application with the help of EntityFramework Code-First approach.

    5. Part 5: Implementing Repository Pattern in MVC Application with EntityFramework.

    6. Part 6: Implementing a generic Repository Pattern and Unit Of Work pattern in MVC Application with

    EntityFramework.

    Pre-requisites

    There are few pre-requisites before we start with the article:

    1. We have the running sample application that we created in the third partof the article series.

    2. We have EntityFramework 4.1 package or DLL on our local file system.

    3. We understand howMVC application is created.

    Code-First Approach

    To achieve a domain driven design, Entity Framework introduced EF 4.1 Code First. In the Code First approach,

    we focus on the domain design or entities/POCO classes first and create classes as per our model requirement.

    We do not have the database of the application, rather we create database automatically from code after defining

    our domain. The database created perfectly matches with the domain we design, so we have to be veryconscious and keen in designing our domain model. It feels exciting to see database created on the fly with the

    help of our entities and XML configuration, without even opening database server.

    No matter, you are not an expert in database, if you are a C# developer, just focus on your model/class creation.

    EntityFramework will take headache of creating and managing database for you.

    http://www.codeproject.com/Articles/620786/Learning-MVC-Part-3-Creating-MVC-Application-Perfohttp://csharppulse.blogspot.in/2013/08/learning-mvc-part-3-creating-mvc.htmlhttp://csharppulse.blogspot.in/http://csharppulse.blogspot.in/2013/09/learning-mvc-part-4-creating-mvc.htmlhttp://www.codeproject.com/Articles/620786/Learning-MVC-Part-3-Creating-MVC-Application-Perfohttp://csharppulse.blogspot.in/2013/09/learning-mvc-part-6-generic-repository.htmlhttp://csharppulse.blogspot.in/2013/09/learning-mvc-part-5repository-pattern.htmlhttp://csharppulse.blogspot.in/2013/09/learning-mvc-part-4-creating-mvc.htmlhttp://csharppulse.blogspot.in/2013/08/learning-mvc-part-3-creating-mvc.htmlhttp://csharppulse.blogspot.in/2013/08/learning-mvc-part-2-creating-mvc.htmlhttp://csharppulse.blogspot.in/2013/08/learning-mvc-part-1-introduction-to-mvc.htmlhttps://docs.google.com/file/d/0B6aCOfU3iep1MVBidFRnNlA1c3c/edit?usp=sharinghttp://csharppulse.blogspot.in/2013/09/learning-mvc-part-4-creating-mvc.htmlhttp://csharppulse.blogspot.in/
  • 8/9/2019 csharppulse.blogspot.in-Learning_MVC_Part_4__Creating_MVC_Application_with_EntityFramework_Code_First_Approac

    http:///reader/full/csharppulseblogspotin-learningmvcpart4creatingmvcapplicationwithentityframeworkcodefirstappr 2/8

    Procedure

    Step 1: Open the MVC application that we created in Learning MVC-Part3in your Visual Studio.

    We can

    clearlysee and

    remember what we used to connect our MVC application to database with the help of entity framework, yes it was

    edmx class and our Model.ttclasses generated from edmx classes.

    Step 2: We dont need the existing data-base, so you can delete the already created database for our part 3application (if created).

    Step 3: We dont need edmx files now, so lets clean our application, wipe out all these classes. Just

    deleteEFDataModel.edmx, Model1.Context.ttand Model1.ttfiles. Now please do not run the application. It will

    give compile time errors, since we were using those classes ;-), Our solution will look like:

    http://www.codeproject.com/Articles/620786/Learning-MVC-Part-3-Creating-MVC-Application-Perfo
  • 8/9/2019 csharppulse.blogspot.in-Learning_MVC_Part_4__Creating_MVC_Application_with_EntityFramework_Code_First_Approac

    http:///reader/full/csharppulseblogspotin-learningmvcpart4creatingmvcapplicationwithentityframeworkcodefirstappr 3/8

    Our old

    solution

    had

    UserList class in Modelsfolder, I have only changed the name of the class for differentiating it with previous

    application, and readability as was in the first part.

    Step 4: As simple as that, just add a class to your solution, and name it MVCDBContext.csas shown in the

    following image:

    Step

    5: Just

    add System.Data.EntityDLL as a reference to the solution if not already added.

  • 8/9/2019 csharppulse.blogspot.in-Learning_MVC_Part_4__Creating_MVC_Application_with_EntityFramework_Code_First_Approac

    http:///reader/full/csharppulseblogspotin-learningmvcpart4creatingmvcapplicationwithentityframeworkcodefirstappr 4/8

    Step 6:

    Use the

    namespace System.Data.Entity in our DBContext class, and inherit the added class fromDBContext

    class,

    DbContext class: According to MSDN, DbContext class is conceptually similar to ObjectContext. To

    define, theObjectContext class is the part of the core EF API in the Microsoft .NET Framework 4 and this is

    our hero class that allows us to perform queries, change tracking and update the database using the strongly

    typed classes that represent our model (entity class). The DbContext is a wrapper around ObjectContext

    that exposes the most commonly used features of ObjectContext as well as provides some simpler shortcuts

    to tasks that are frequently used but complicated to code directly with ObjectContext. Simplfied alternative to

    ObjectContext and is the primary object for interacting with a database using a specific model.

    Step 7: Add a DBSet property to the DbContext class that we created:

    public DbSet Users { get; set;

    }

    User, defined in angular brackets, is the model that we created in Modelsfolder, so our MVCDBContext class

    looks like:

    using System;

    using System.Collections.Generic;

    using System.Data.Entity;

    using System.Linq;

    using System.Web;

    using LearningMVC.Models;

    namespace LearningMVC

    {

    public class MVCDBContext : DbContext

    {

    public DbSet Users { get; set;

    }

    }

    }

  • 8/9/2019 csharppulse.blogspot.in-Learning_MVC_Part_4__Creating_MVC_Application_with_EntityFramework_Code_First_Approac

    http:///reader/full/csharppulseblogspotin-learningmvcpart4creatingmvcapplicationwithentityframeworkcodefirstappr 5/8

    Thats it, our 90% work is done?

    DbSet property: It is a simplified alternative to ObjectSet and is used to perform CRUD operations against a

    specific type from the model.

    By default, the name of the DbContext class will be the name our database that will automatically be created, s

    be wise to select the name of context class, else it could be handled in web.configas well.

    The name of model will be the name of Table in database and properties of model will be the columns of the table.

    Our Heroes

    Both

    DbContext

    and DbSet

    are our super

    heroes, in

    creating and

    dealing with

    database

    operations,

    and make us

    far

    abstracted,

    providing

    ease of use to

    us.

    When we are

    working with

    DbContext,

    we are in real

    working withentity sets. DbSet represents a typed entity set that is used to perform create, read, update, and delete

    operations. We are not creating DbSet objects and using them indepedently. DbSet can be only used with

    DbContext.

    Step 8: Define a connection string in web.configfile, you can remove previously defined connection string, the

    new connection string will somewhat look like:

  • 8/9/2019 csharppulse.blogspot.in-Learning_MVC_Part_4__Creating_MVC_Application_with_EntityFramework_Code_First_Approac

    http:///reader/full/csharppulseblogspotin-learningmvcpart4creatingmvcapplicationwithentityframeworkcodefirstappr 6/8

    The

    name of

    the

    connection string will be the name of the DbContect that we defined, i.e., MVCDbContext.

    Step 9: Now, we just have to modify the access method in controllers, earlier, when we created application in third

    part, we were accessing the context class from the modelcontext class that was generated from edmx file.

    Edmx file was added having reference to already created database.

    But now the case is different, we dont have a database now, well access the table and columns using our

    MVCDBContext class in controllers, so just change the following line of code used in Actions of earlier

    application:

    var dbContext = new MVCEntities()

    ;

    to

    var dbContext = new

    MVCDBContext();

    Job done.

    Just Hit F5, and youll see:

    How does the application run, where is the database??? Dude, go back to your databaseserver,

    and

    check

    for

    database:

  • 8/9/2019 csharppulse.blogspot.in-Learning_MVC_Part_4__Creating_MVC_Application_with_EntityFramework_Code_First_Approac

    http:///reader/full/csharppulseblogspotin-learningmvcpart4creatingmvcapplicationwithentityframeworkcodefirstappr 7/8

    We see

    our

    database is created, with the name MVCDB, thats the magic of EntityFramework. Now we can perform all the

    CRUD operations on this database, using our application. Just create a new user.

    In

    database we see, user created.

  • 8/9/2019 csharppulse.blogspot.in-Learning_MVC_Part_4__Creating_MVC_Application_with_EntityFramework_Code_First_Approac

    http:///reader/full/csharppulseblogspotin-learningmvcpart4creatingmvcapplicationwithentityframeworkcodefirstappr 8/8

    By

    default,

    integer

    property with ID in its name of model will be the primary key in the database, in our caseUserId, or you can

    define the primary key in the model too.

    Conclusion

    Now we know how to play with EntityFramework to create database as per our domain model from our code,

    we have already moved ahead to advanced concepts of MVC and Entity Framework.

    When

    we see

    the

    definition of DbContext, it uses the terms Repository Pattern and Unit of Work Pattern. Well discuss these more

    in detail in my next article.

    For more informative articles,visit my blogA Practical Approach.Happy coding! :-)

    http://csharppulse.blogspot.in/