Organizing your Data Access Layer

code-organizationentity-frameworkorm

I am using Entity Framework as my ORM in an ASP.Net application. I have my database already created so ended up generating the entity model from it. What is a good way to organize files/classes in the data access layer. My entity framework model is in a class library and I was planning on adding additional classes per Entity(i.e per database table) and putting all the queries related to those tables in their respective classes. I am not sure if this is a right approach and if it is then where do the queries requiring data from multiple tables go?
Am I completely wrong in organizing my files based on entities/tables and should I organize them based on functional areas instead.

Best Answer

In the project I'm working on now we're using ASP.NET MVC and Entity Framework 4.1. We also had a database first, but we went with the idea of using the POCO objects generated from the DBSet based T4 templates.

In our project, we've got one assembly called business which has a data namespace. Inside this namespace is where the DBContext and generated POCO's live. We don't touch this once the data access has been created. Now in addition, we have a set of repositories which we're using to; 1: run the basic CRUD needs and 2: create and deliver custom Data Transfer Objects up to the front end.

In the front end is where we're using the data annotations either on the custom DTO's or on custom ViewModels for specific needs. Our assumption is that we should validate the data coming from the front end as quickly as needed and then pass back clean models to the repositories. We're not really too worried about the entity change tracking or anything like that for entity framework so long as we save and pull successfully.

So far this has worked for us. Hope this helps you some, and good luck on your project.