【问题标题】:How to create three tier solution for Entity framework如何为实体框架创建三层解决方案
【发布时间】:2011-08-18 01:08:12
【问题描述】:

我在一个解决方案中创建了三个项目,一个 Web 应用程序,两个用于 DAL 和 BLL 的类库。在 DAL 层创建了 Entity Framework 模型,并在 BLL 项目中引用了 DAL 库。

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

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

【问题讨论】:

    标签: .net asp.net entity-framework soa


    【解决方案1】:

    听起来您的 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 附带的 Entity Framework 和我使用过的 Linq-To-SQL 都是如此,它可能适用于最新版本的 EF,但使用 Code-First 和其他事情可能有一种方法可以避免这个额外的数据传输对象步骤,尽管使用面向服务的架构,DTO 可能是最好的方法。

    【讨论】:

    • 感谢@Nate,Data-Transfer-Object 丢失并遇到了麻烦。
    猜你喜欢
    • 2011-10-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-30
    • 1970-01-01
    • 1970-01-01
    • 2011-11-16
    • 1970-01-01
    相关资源
    最近更新 更多