ASP.NET MVC web application with Entity Framework – Part 2.

As mentioned in the previous post, this part will show the DAL project of our Movie Inventory ASP.NET MVC web application.

This small Data Access Layer class library project contains only our context declaration, the relations of the entities and our generic DbSet method. This class handles the SQL connection and sets the Entity Framework to disable lazy loading and proxy creation. I don’t want to write the details of these, there are many many forums on the internet that describes it. The main reason is, that if you use tables with relations between each other, you should turn of lazy loading, so you can easily get a value of a foreign key from another table.

When adding this new Class Library project to the solution, add Entity Framwork as reference from NuGet Package Manager and of course the DTO project too. Drag and drop the MovieInventoryContext.cs file from the previous DTO project to this DAL project. You can delete this file from DTO. Add DTO in the using area of this file here in DAL project.

Add the following 3 lines to the constructor to disable lazy loading:

public MovieInventoryContext() : base("name=MovieInventoryContext")
    Configuration.LazyLoadingEnabled = false;
    Configuration.ProxyCreationEnabled = false;

Comment out the automatic generated DbSet lines:

//public virtual DbSet Category { get; set; }
//public virtual DbSet Format { get; set; }
//public virtual DbSet Inventory { get; set; }
//public virtual DbSet Movie { get; set; }

Create our own DbSet generic method:

public DbSet GetDbSet() where T : BaseIdentity
    return base.Set();

For possible further usage create this static method:

public static MovieInventoryContext Create()
    return new MovieInventoryContext();

The file now should look like this:

Don’t forget to modify later your Web.config file in the UI project. It will contain the connection string for the SQL server that this class will use.

The next part is the Business Logic Layer. This will contain the Repository Pattern, Unit Of Work. From the UI we can access the database through the Unit Of Work interfaces. The person who is responsible for BLL can extend the Repository Pattern with any kind of interfaces for the frontend developers. Frontend developers can only manipulate those db stuffs, that BLL allows. Nice, isn’t it?

Your solution should like like this: