• How to Add ADO.NET Data Model in ASP.NET MVC

    by  • January 9, 2016 • Microsoft ADO.NET, Microsoft ASP.NET MVC • 0 Comments

    Here we would describe how to add a data model to interact with the database. ADO.NET entity framework data model handles the database interaction with the application. We don’t directly interact with the database rather we retrieve the data by writing SQL queries.

    We can add entity data model with the following simple steps

    1. Right click on the package name, in our program we right click on BooksCollection
    2. Click Add, then select new item
    3. Select ADO.NET Entity Data Model then name it and click Add as shown in the figure below; ADO NET MODEL
    4. Name the entity Model like I did name it as ‘Store’
    5. A new window ‘Choose Model Contents ‘ will appear. Here we have to select a data model that suits our application. As shown in the figure; Entity data model
    6. Here we choose Code First from database that creates a Code First model based on an existing database. We can choose the database connection, settings for the model, and database objects to include in the model.
    7. A window choose data connection will appear, We will select our database ‘BookStore.mdf ’ from drop down arrow list. Here connection string will generate and this connection string will save in the Web.config file                                         . choose database
    8. Now a new window ‘Choose Your Database and Settings’ will appear. Now we include database objects in our model, we will choose tables .dataobjects
    9. Click on finish

    When we click finish button, Some new files are listed in Solution Explorer like store.cs , book.cs. The store.cs file is database connection file (DB Context) which is used to create database connection. Lets look at the store.cs file;

    store.cs

    The DBContext class is responsible for the application interaction with database so our entity model class store is inherited from the DBContext class. In the above code there is a method onModelCreating(), this method is called when the model is intialized.  Then we map each entity to the database using modelBuilder.Entity<>.

    When we add a ADO.NET model in our application, a ‘Connection String ‘ is generated and saved in Web.config file. As shown below;

    The Web.Config file holds the configuration information for our project. Connection string is used to connect our application with the database.




    Namecheap.com

    Leave a Reply