2011-05-03 68 views
7

我在解决方案,一个Web应用程序,DAL和BLL的两个类库中创建了三个项目。在DAL层中创建了实体框架模型,并在BLL项目中引用了DAL库。如何为实体框架创建三层解决方案

当我从Web应用程序项目调用BLL对象时遇到问题,它说我需要引用实体框架。我不想在Web应用程序项目中对DAL库对象进行任何依赖。

是否有关于使用实体框架构建清洁三层应用程序的具体指导。

回答

17

您BLL的声音会暴露您在DAL中添加的entity类。您需要在BLL中创建包装类(即POCO),并从DAL中返回它们,而不是实体。

这可能是你做什么:

// 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); 

这可能是你应该做什么:

// 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); 

这是与附带的实体框架如此。 NET 3.5SP1和Linq-To-SQL,我已经使用了这两个版本,它可能适用于EF的最新版本,但使用Code-First和其他方法可能会避免这种额外的数据传输尽管采用面向服务架构,但DTO可能是最好的选择。

+0

谢谢@Nate,数据传输对象错过了并陷入困境。 – inlokesh 2011-05-03 21:10:31

相关问题