Dot-Net

如何為實體框架創建三層解決方案

  • May 3, 2011

我在一個解決方案中創建了三個項目,一個 Web 應用程序,兩個用於 DAL 和 BLL 的類庫。在 DAL 層創建了 Entity Framework 模型,並在 BLL 項目中引用了 DAL 庫。

當我從遇到問題的 Web 應用程序項目中呼叫 BLL 對象時,它說我需要引用實體框架。我不希望對 Web 應用程序項目中的 DAL 庫對像有任何依賴。

是否有關於使用實體框架建構乾淨的三層應用程序的具體指導。

聽起來您的 BLL 正在公開entity您在 DAL 中添加的類。您需要在 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 可能是最好的方法。

引用自:https://stackoverflow.com/questions/5875546