Entity Framework and Layer Separation in C#

centity-frameworklayers

I'm trying to work a bit with Entity Framework and I got a question regarding the separation of layers.

I usually use the UI -> BLL -> DAL approach and I'm wondering how to use EF here.

My DAL would usually be something like

GetPerson(id)
{
    // some sql
    return new Person(...)
}

BLL:

GetPerson(id)
{
    Return personDL.GetPerson(id)
}

UI:

Person p = personBL.GetPerson(id)

My question now is: since EF creates my model and DAL, is it a good idea to wrap EF inside my own DAL or is it just a waste of time?

If I don't need to wrap EF would I still place my Model.esmx inside its own class library or would it be fine to just place it inside my BLL and work some there?

I can't really see the reason to wrap EF inside my own DAL but I want to know what other people are doing.

So instead of having the above, I would leave out the DAL and just do:

BLL:

GetPerson(id)
{
    using (TestEntities context = new TestEntities())
    {
            var result = from p in context.Persons.Where(p => p.Id = id)            
                    select p;
    }
}

What to do?

Best Answer

The example you provide is hardly layered architecture. I know it is intentionally simplified, but:

Your presentation layer is directly tied to the Person entity. This is OK only in simplest cases, and definitely not when you are trying to define your layers.

The GetPerson method is also using a rather bad practice of creating a new context for each call. You should get the context in the constructor, and it will be provided by your IOC container.

A simple, yet effective structure I have used is:

  • Project.Core - contains view models and interfaces.
  • Project.DAL - with my EDMX and generated code.
  • Project.BLL - business logic.
  • Project.Web - the web app itself.

It is important to note that:

  • Core is not dependent on any other solution.
  • DAL is not dependent on any other solution.
  • Project.Web depends on Core, but not on DAL nor BLL.
  • BLL depends on Core and DAL.