Asp.Net Mvc Creating Dbcontext And Entities Complete Guide

 Last Update:2025-06-23T00:00:00     .NET School AI Teacher - SELECT ANY TEXT TO EXPLANATION.    9 mins read      Difficulty-Level: beginner

Understanding the Core Concepts of ASP.NET MVC Creating DBContext and Entities

ASP.NET MVC Creating DbContext and Entities: A Comprehensive Guide

Understanding DbContext

The DbContext class plays a fundamental role in Entity Framework. It acts as the bridge between your application and the database, serving multiple purposes such as:

  • Change Tracking: DbContext automatically tracks changes made to entities in state.
  • Query Generation: Converts LINQ queries to SQL, executes them, and materializes results into entity instances.
  • Connection Management: Manages connections between the application and the database.
  • Caching: Maintains an identity map to prevent duplicate entity instances being loaded from the same database row.

Creating a DbContext involves defining classes that inherit from the DbContext base class in the Entity Framework library. Here’s a step-by-step guide:

  1. Install Entity Framework: Ensure your project has Entity Framework installed. You can add it via NuGet Package Manager with the command:

    Install-Package EntityFramework
    
  2. Define the DbContext Class: Create a new class that inherits from DbContext. Within this class, define DbSet properties that represent the collections of entities you want to interact with in the database.

    using System.Data.Entity;
    
    public class MyDbContext : DbContext
    {
        public MyDbContext() : base("name=MyConnectionString")
        {
        }
    
        public DbSet<Product> Products { get; set; }
        public DbSet<Category> Categories { get; set; }
    }
    

    Replace "MyConnectionString" with the actual connection string to your database.

Defining Entities

Entities in Entity Framework represent tables in your database. Each entity class typically corresponds to a table in the database, and each property of the class corresponds to a column. Let's look at creating simple entities like Product and Category.

  1. Create Entity Classes: Define entity classes that represent your domain model. For example:

    public class Product
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public decimal Price { get; set; }
        public int CategoryId { get; set; } // Foreign key
        public virtual Category Category { get; set; } // Navigation property
    }
    
    public class Category
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public virtual ICollection<Product> Products { get; set; } // Navigation property
    }
    
  2. Annotate Properties with DataAnnotations: Use attributes like [Key], [Required], [StringLength], etc., for additional configuration.

    using System.ComponentModel.DataAnnotations;
    using System.ComponentModel.DataAnnotations.Schema;
    
    public class Product
    {
        [Key]
        public int Id { get; set; }
    
        [Required]
        [StringLength(100)]
        public string Name { get; set; }
    
        [Column(TypeName = "decimal(18, 5)")]
        public decimal Price { get; set; }
    
        public int CategoryId { get; set; }
        [ForeignKey("CategoryId")]
        public virtual Category Category { get; set; }
    }
    
    public class Category
    {
        [Key]
        public int Id { get; set; }
    
        [Required]
        [StringLength(50)]
        public string Name { get; set; }
    
        public virtual ICollection<Product> Products { get; set; }
    }
    
  3. Configure Entity Relationships: Use fluent API for configuring relationships between entities in more complex scenarios.

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Product>()
            .HasRequired(p => p.Category) // Each product must have a category
            .WithMany(c => c.Products)    // One category contains many products
            .HasForeignKey(p => p.CategoryId);
    }
    

Important Information:

  • Connection Strings: Configure your connection strings in the Web.config file.

    <connectionStrings>
        <add name="MyConnectionString" connectionString="Data Source=(localdb)\MSSQLLocalDB; Initial Catalog=MyDatabase; Integrated Security=True;" providerName="System.Data.SqlClient" />
    </connectionStrings>
    
  • Database Initialization: Entity Framework provides various strategies for initializing the database. You can configure these settings in your context class.

    public class MyDbContextInitializer : DropCreateDatabaseIfModelChanges<MyDbContext>
    {
        protected override void Seed(MyDbContext context)
        {
            var categories = new List<Category>
            {
                new Category { Name = "Electronics" },
                new Category { Name = "Clothing" },
                new Category { Name = "Books" }
            };
    
            categories.ForEach(c => context.Categories.Add(c));
            context.SaveChanges();
        }
    }
    
    Database.SetInitializer(new MyDbContextInitializer());
    
  • Lazy vs Eager Loading: Understand the differences between lazy loading (entities loaded on-demand) and eager loading (loaded in advance).

    • Eager loading: Use Include method.
      var products = db.Products.Include(p => p.Category).ToList();
      
    • Lazy Loading: Enable by default in EF6, but can be turned off for performance reasons.
      context.Configuration.LazyLoadingEnabled = false;
      
  • Code First vs. Database First: Choose between Code First (define entities first, then create the database) or Database First (start with an existing database, generate entity classes).

    • Code First: Ideal for greenfield projects where you’re designing both the application and the database from scratch.
    • Database First: Useful when working with legacy databases.
  • CRUD Operations: Implement CRUD operations using the DbContext to create, read, update, and delete entities.

    // Create
    var product = new Product { Name = "Laptop", Price = 1200 };
    db.Products.Add(product);
    
    // Read
    var products = db.Products.ToList();
    
    // Update
    var productToUpdate = db.Products.Find(1);
    productToUpdate.Price = 999;
    db.Entry(productToUpdate).State = EntityState.Modified;
    
    // Delete
    var productToDelete = db.Products.Find(2);
    db.Products.Remove(productToDelete);
    
    db.SaveChanges(); // Apply changes to the database
    

By understanding and effectively utilizing DbContext and entities, you can streamline data management in your ASP.NET MVC applications, leading to cleaner code and greater developer productivity. Remember to always consider how EF will map your entities to the database schema and ensure your configurations align with your application’s requirements.

Online Code run

🔔 Note: Select your programming language to check or run code at

💻 Run Code Compiler

Step-by-Step Guide: How to Implement ASP.NET MVC Creating DBContext and Entities

Step 1: Create a New ASP.NET MVC Project

  1. Open Visual Studio.
  2. Select File > New > Project...
  3. Choose ASP.NET Web Application (.NET Framework) under the Web category.
  4. Enter a name for your project, e.g., MvcAppWithEf, and click OK.
  5. In the next window, select MVC template from the list of options and ensure Authentication is set to No Authentication or any other authentication method you prefer. Click Create.

Step 2: Install Entity Framework

Entity Framework (EF) can be added via NuGet Package Manager.

  1. In Solution Explorer, right-click on the project (e.g., MvcAppWithEf) and select Manage NuGet Packages....
  2. In the NuGet Package Manager, go to the Browse tab and search for EntityFramework.
  3. Select the package by Microsoft and click Install. Agree to any terms and prompts that are shown.

Step 3: Create a Model Class

You will create an entity class to represent the data model. Let's create a simple Employee class.

  1. Right-click on the Models folder in Solution Explorer (create it if it doesn't exist).
  2. Add > New Item....
  3. Choose Class and name it Employee.cs.
  4. Add the following code to the Employee.cs file:
using System.ComponentModel.DataAnnotations;

namespace MvcAppWithEf.Models
{
    public class Employee
    {
        [Key]
        public int Id { get; set; }

        [Required]
        [StringLength(50)]
        public string FirstName { get; set; }

        [Required]
        [StringLength(50)]
        public string LastName { get; set; }

        public string Email { get; set; }

        public int Age { get; set; }

        public decimal Salary { get; set; }
    }
}

Step 4: Create ApplicationDbContext Class

This class will serve as a context to the database operations.

  1. Right-click on the Models folder in Solution Explorer.
  2. Add > New Item....
  3. Choose Class and name it ApplicationDbContext.cs.
  4. Add the following code to the ApplicationDbContext.cs file:
using System.Data.Entity;

namespace MvcAppWithEf.Models
{
    public class ApplicationDbContext : DbContext
    {
        public ApplicationDbContext() : base("DefaultConnection")
        {
        }

        public virtual DbSet<Employee> Employees { get; set; }
    }
}

Step 5: Configure Connection String in Web.config

You need to specify the connection string for the application to connect to your database.

  1. Open the Web.config file located at the root of your project.
  2. Find the <connectionStrings> section and add the following connection string:
<connectionStrings>
    <add name="DefaultConnection"
         connectionString="Data Source=(LocalDb)\MSSQLLocalDB;Initial Catalog=MvcAppWithEf;Integrated Security=True;"
         providerName="System.Data.SqlClient" />
</connectionStrings>

Step 6: Enable Migrations

  1. Open the Package Manager Console (Tools > NuGet Package Manager > Package Manager Console).
  2. Execute the following command to enable migrations:
Enable-Migrations

Entity Framework will create a Migrations folder in your project with Configuration.cs inside it.

Step 7: Create the Initial Migration

  1. In the Package Manager Console, execute the next command to create the initial migration:
Add-Migration InitialCreate

Entity Framework generates a new migration class in the Migrations folder, which includes the SQL commands to create the database tables.

Step 8: Update Database

  1. To apply the migrations to the database, run the following command in the Package Manager Console:
Update-Database

This command will generate and apply the SQL to the specified database, creating the necessary tables.

Step 9: Create Controller and Views

  1. In Solution Explorer, right-click on the Controllers folder and select Add > Controller....
  2. Choose MVC 5 Controller with views, using Entity Framework.
  3. Name the controller EmployeesController.
  4. Set the Model class to Employee and choose ApplicationDbContext as the data context class.
  5. Click Add.

Visual Studio will generate a complete controller with CRUD actions and corresponding views for Employee.

Step 10: Display Employees on Home Page

To show a list of employees on the home page of the application:

  1. Open the HomeController class in the Controllers folder.
  2. Modify the Index action method to fetch employees:
public ActionResult Index()
{
    using (var context = new ApplicationDbContext())
    {
        return View(context.Employees.ToList());
    }
}
  1. Open the Index.cshtml view in the Views/Home folder and modify it to display the list of employees:
@{
    ViewBag.Title = "Home Page";
}

@section featured {
    <section class="featured">
        <div class="content-wrapper">
            <hgroup class="title">
                <h1>@ViewBag.Title.</h1>
                <h2>Our Employees</h2>
            </hgroup>
            <table>
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>Name</th>
                        <th>Email</th>
                        <th>Age</th>
                        <th>Salary</th>
                    </tr>
                </thead>
                <tbody>
                    @foreach (var employee in Model)
                    {
                        <tr>
                            <td>@employee.Id</td>
                            <td>@employee.FirstName @employee.LastName</td>
                            <td>@employee.Email</td>
                            <td>@employee.Age</td>
                            <td>@employee.Salary</td>
                        </tr>
                    }
                </tbody>
            </table>
        </div>
    </section>
}

Step 11: Insert Sample Data

You may want to insert some sample data to test the application.

  1. Open the Application_Start method in Global.asax.cs and add the following code:
protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();
    FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
    RouteConfig.RegisterRoutes(RouteTable.Routes);
    BundleConfig.RegisterBundles(BundleTable.Bundles);

    using (var context = new ApplicationDbContext())
    {
        // Add a default employee
        var employee = new Employee
        {
            FirstName = "John",
            LastName = "Doe",
            Email = "john.doe@example.com",
            Age = 30,
            Salary = 50000
        };

        if (!context.Employees.Any(e => e.FirstName == "John" && e.LastName == "Doe"))
        {
            context.Employees.Add(employee);
            context.SaveChanges();
        }
    }
}

Step 12: Run the Application

  1. Press F5 or click the Start button in Visual Studio to run your application.
  2. Navigate to the home page (http://localhost:<port>/). You should see the list of employees displayed.

Summary

You have successfully created a DbContext and entities, enabled migrations, updated the database, created a controller and views, and inserted sample data in an ASP.NET MVC application using Entity Framework.

Top 10 Interview Questions & Answers on ASP.NET MVC Creating DBContext and Entities

Top 10 Questions and Answers on ASP.NET MVC: Creating DBContext and Entities

1. What is a DbContext in ASP.NET MVC?

  • Answer: A DbContext in ASP.NET MVC represents a session with the database that can be used to query and save entities. It's an essential component of Entity Framework which is responsible for mapping between the in-memory data and the stored database records. DbContext holds the DbSet objects that allow you to access the database entities, and it also handles change tracking and persistence logic.

2. How do I create a Model and corresponding Entity in ASP.NET MVC?

  • Answer: In ASP.NET MVC, your models usually represent the tables in your database. To create an entity, you define a model class.

3. How do I create a DBContext in ASP.NET MVC?

  • Answer: Create a new class that inherits from DbContext. Add DbSet properties for each entity.
public class AppDbContext : DbContext
{
    public DbSet<Employee> Employees { get; set; }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.UseSqlServer(@"Server=(localdb)\mssqllocaldb;Database=MyDB;");
    }
}

The above code creates a DbContext class called AppDbContext with one DbSet property for the Employee entity.

4. Can I configure my DbContext using a connection string in the configuration file instead of code?

  • Answer: Yes, it is recommended practice to use a connection string stored in your Web.config or appsettings.json.
<!-- In Web.config -->
<connectionStrings>
    <add name="DefaultConnection" connectionString="Server=(localdb)\mssqllocaldb;Database=MyDB;" providerName="System.Data.SqlClient" />
</connectionStrings>

And then in the DbContext:

public class AppDbContext : DbContext
{
    public DbSet<Employee> Employees { get; set; }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.UseSqlServer(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString);
    }
}

For .NET Core, you would use appsettings.json:

{
  "ConnectionStrings": {
    "DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=MyDB;"
  },
}

And inject the configuration in your Startup.cs:

You May Like This Related .NET Topic

Login to post a comment.