The main class that coordinates Entity Framework functionality for a given data model is the database context class. You create this class by deriving from the System.Data.Entity.DbContext class. In your code you specify which entities are included in the data model. You can also customize certain Entity Framework behavior. In the code for this project, the class is named MVC3EntityFrameworkDemo.
Create a DAL folder. In that folder create a new class file named SchoolContext.cs, and replace the existing code with the following code:
using System;
using System.Collections.Generic;
using System.Data.Entity;
using MVC3EntityFrameworkDemo.Models;
using System.Data.Entity.ModelConfiguration.Conventions;
namespace MVC3EntityFrameworkDemo.Models
{
public class SchoolContext : DbContext
{
public DbSet<Student>Students{get;set;}
public DbSet<Enrollment>Enrollments{get;set;}
public DbSet<Course>Courses{get;set;}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
}
}
}
This code creates a DbSet property for each entity set. In Entity Framework terminology, an entity set typically corresponds to a database table, and an entity corresponds to a row in the table.
The statement in the OnModelCreating method prevents table names from being pluralized. If you didn't do this, the generated tables would be named Students, Courses, and Enrollments. Instead, the table names will be Student, Course, and Enrollment. Developers disagree about whether table names should be pluralized or not. This tutorial uses the singular form, but the important point is that you can select whichever form you prefer by including or omitting this line of code.
(This class is in the Models namespace, because in some situations Code First assumes that the entity classes and the context class are in the same namespace.)
Getting Started with Entity Framework Code First
Introduction to POCO classes in Entity Framework
Create First MVC application in Visual Studio 2010
Creating the Entity Framework Data Model in Visual Studio
Create classes for each entity using Entity Framework
Create the Database Context using Entity Framework
Setting the Connection String in MVC Asp.Net Application
Creating a Controller and Views in MVC application
0 comments:
Post a Comment