I have 3 projects in my solution :

  • An ASP MVC project
  • A console app project
  • A class library project (the DataAccessLayer)

I didn't want to recreate an ADO.net entity data model for each project so I've "simply" created a new class library project and added the ADO.net entity data model inside it. Is it an usual way to create a data access layer? Any improvements?

The DbContext (DAL project)

public partial class ModelContainer : DbContext
    public ModelContainer(): base("name=ModelContainer")

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
        throw new UnintentionalCodeFirstException();

    public virtual DbSet<Thread> Thread { get; set; }
    public virtual DbSet<Post> Post { get; set; }
    public virtual DbSet<Forum> Forum { get; set; }
    public virtual DbSet<SubForum> SubForum { get; set; }
    public virtual DbSet<Author> Author { get; set; }

Use of the DAL (ASP MVC Controller)

public class ForumController : Controller
    private static ModelContainer db = new ModelContainer();

    public ActionResult Index()
        //returns a list of forums
        return View(db.Forum);
  • 1
    Yes, this is the most common practice.
    – Alon
    Commented Jun 3, 2018 at 22:32

1 Answer 1


This is the most used method to implement database access code. Improvements:

  • Add a business layer isolating your console/web apps from accessing the data access layer directly. The business layer will provide a business context for the operations. This context abstracts the operations and shortens the required amount of code in the presentation layer.
  • Create one or more classes to encapsulate the database operations. So the business layer does not access the context directly. Adding Interfaces as a contract will give you a lot of flexibility. Just to mention the ability to mock these classes in unit tests and the ability to switch implementation.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.