How to build a three-tier Entity Framework solution

.net asp.net entity-framework soa

Question

I made a solution with three projects: a web application, two class libraries for DAL, and a BLL class library. In the DAL layer, the Entity Framework model was created, and the DAL library was referred to in the BLL project.

There are issues when I call BLL objects from the web application project; it says I need to reference entity framework. I don't want the web application project to be dependent on any DAL library objects.

Is there a precise set of instructions for utilizing Entity Framework to create a tidy three-tier application.

1
8
5/3/2011 9:07:21 PM

Accepted Answer

It seems that your BLL is revealing theentity classes in the DAL that you inserted. You must develop POCO-based wrapper classes in the BLL and return them instead of the DAL entities.

You're probably doing the following:

// DAL
// .edmx file generated entities
public IQueryable<TableEntity> GetTableEntities()
{
     // read from entity framework and return
}

// BLL
public IEnumerable<TableEntity> ReadTableEntitiesForUser(int userID);
{
    var d = new DAL();
    var entities = d.GetTableEntities();
    // restrict to entites this user "owns"
    entities = entities.Where(e => e.OwnerID.Equals(userID));
    return entities;        
}

// WebApp
var b = new BLL();
var myEntities = b.ReadTableEntitiesForUser(1234);

You'll probably be performing the following:

// DAL
// .edmx file generated entities
public IQueryable<TableEntity> GetTableEntities()
{
     // read from entity framework and return
}

// BLL
public class TableEntityDTO 
{
    public int ID { get; set; }
    public string Name { get; set; }
    // continue on for each column in the table
    // and make a DTO class for each table in your database
}
public IEnumerable<TableEntityDTO> ReadTableEntitiesForUser(int userID);
{
    var d = new DAL();
    var entities = d.GetTableEntities();
    // restrict to entites this user "owns"
    entities = entities.Where(e => e.OwnerID.Equals(userID));
    // convert from "Entity Framework Object" to "BLL Object"
    foreach(var e in entities)
    {
        yeild return new TableEntityDTO() { ID = e.ID, Name = e.Name };
    }
}

// WebApp
var b = new BLL();
var myEntities = b.ReadTableEntitiesForUser(1234);

This is true for the Entity Framework that came with.NET 3.5SP1 and for Linq-To-SQL, both of which I have used a little. It might also be true for the most recent versions of EF, but there may be a way to get around this extra Data-Transfer-Object step using Code-First and other techniques. However, for a Service Orientated Architecture, DTOs are probably the best option.

19
5/3/2011 9:01:31 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow