0

我正在使用 3 层(UI、BLL、DAL)架构并在这些层之间使用 BusinessObjects(又名数据传输对象 - DTO)。假设我有以下 DTO:

public class EmployeeDTO
{
    public int EmpID { get; set; }
    public string Name { get; set; }
    public ICollection<EmailDTO> EmailList { get; set; }
}

public class EmailDTO
{
    public int EmailID { get; set; }
    public string Message { get; set; }
}

我想在使用 EmployeeDTO 时延迟加载 EmailList 集合,因为它可能包含大量数据。所以基本上 EmployeeDTO 将在 DAL 级别创建(没有电子邮件收集)并通过 BLL 发送回 UI。此时我如何才能在 UI 级别延迟加载 EmailList。我的代码(省略细节)类似于以下内容:

用户界面

{
    EmployeeDTO empDTO = new EmployeeBLL().GetEmployeeByID (id);
}

BLL

public EmployeeDTO GetEmployeeByID (id)
{
    return new EmployeeDAL().GetEmployeeByID (id);
}

达尔

public EmployeeDTO GetEmployeeByID (id)
{
    reader = get employee data by id...

    EmployeeDTO empDTO = new EmployeeDTO ();
    empDTO.EmpID = reader [1];
    empDTO.Name  = reader [2];
    // I can load the email list but i dont
    return empDTO;
}

现在在 DAL 级别,当我使用empDTO.EmailList ()时,它应该延迟加载数据。我怎么能这样做。我需要一个干净的解决方案(请注意我没有使用任何 ORM)。谢谢。

4

1 回答 1

2

首先 - 将电子邮件声明为虚拟:

public class EmployeeDTO
{
    public int EmpID { get; set; }
    public string Name { get; set; }
    public virtual ICollection<EmailDTO> EmailList { get; set; }
}

接下来 - 创建类,它继承自EmployeeDTO并提供延迟加载功能:

public class LazyEmployeeDTO : EmployeeDTO
{
    public override ICollection<EmailDTO> EmailList
    {
        get 
        {
            if (base.EmailList == null)
               base.EmailList = LoadEmails();

            return base.EmailList;
        }

        set { base.EmailList = value; }
    }

    private ICollection<EmailDTO> LoadEmails()
    {
        var emails = new List<EmailDTO>();
        // get emails by EmpID from database
        return emails;            
    }
}

最后 -LazyEmployeeDTO从 DAL 返回,但要确保客户端依赖于简单EmployeeDTO

public EmployeeDTO GetEmployeeByID (id)
{
    reader = get employee data by id...

    EmployeeDTO empDTO = new LazyEmployeeDTO();
    empDTO.EmpID = reader[1];
    empDTO.Name  = reader[2];
    // do not load emails
    return empDTO;
}

其余代码应保持原样。这个懒惰的员工将充当基础员工的代理,客户不会知道他们没有使用EmployeeDTO.

于 2013-07-29T17:06:50.283 回答