在 n 层系统中,您应该从数据访问层向业务层返回哪些对象 [英] What objects should you return from the data access layer to the business layer an n-tier system

查看:14
本文介绍了在 n 层系统中,您应该从数据访问层向业务层返回哪些对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,如果您有一个名为 Person(ID、Name 等)的数据库表,那么数据访问层应该将什么样的对象返回给业务层?我在想这样的事情:

If you have, for example, a database table called Person (ID,Name etc) what kind of object should the data access tier return to the business tier? I'm thinking something like this:

//data access tier
public class DataAccess{

   public interface IPerson{
      int ID{ get; set; }
      string Name{ get; set; }
   }

   internal class Person : IPerson{
      private int id;
      private string name;

      public int ID{ get{return id; } set{ id=value; } }
      public int Name{ get{retutn name; } set{ name=value; }
   }

   public static IPerson GetPerson(int personId)
   {
      //get person record from db, populate Person object
      return person;  
   }
}

//business tier
public class Person : IPerson{
   private int id;
   private string name;

   public int ID{ get{return id;} set{id=value;} }
   public string Name{ get{return name;} set{name=value;} }

   public void Populate(int personId){
      IPerson temp = DataAccess.GetPerson(personId);
      this.ID = temp.ID;
      this.Name = temp.Name;
   }
}

但这一切似乎有点麻烦?这个问题有更优雅的解决方案吗?我应该从数据访问层返回一个 DataRow 到业务层吗?

But this all seems a little cumbersome? Is there a more elegant solution to this problem? Should I return a DataRow from the data access layer to the business layer instead?

推荐答案

您无需在数据访问层 (DAL) 中重复类定义.

You don't need to repeat the class definition in your data access layer (DAL).

您可以在单独的程序集中将业务实体创建为哑"容器,例如你的 Person 类可以是:-

You can create your business entities as 'dumb' containers in a separate assembly, e.g. your Person class can just be:-

public class Person
{
    int ID { get; set: }
    string Name { get; set: }
}

然后,您可以为您的 DAL 提供对业务实体层的引用.您的控制器对象,无论它们是在单独的业务逻辑层中,还是在您的 UI 层中,都可以调用 DAL,后者可以创建一个业务实体,从数据库中填充它并将其返回给您的控制器.

Then, you can give your DAL a reference to the business entities layer. Your controller objects, whether they are in a separate business logic layer, or within your UI layer, can then just call the DAL, which can create a business entity, populate it from the database and return it to your controller.

这篇文章 Imar Spaanjaars 对这种模式有很好的解释.

This article by Imar Spaanjaars has a nice explanation of this pattern.

这篇关于在 n 层系统中,您应该从数据访问层向业务层返回哪些对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆