【发布时间】:2014-08-08 20:55:51
【问题描述】:
对于这个问题,我真的找不到令人满意的解决方案。我有一个 n 层应用程序:
- 用户界面
- 展示(域模型用作 DTO,然后展示 ViewModel)
- 业务层(领域模型)
- 存储库和 DAL(数据模型)
我的问题是我需要在我的业务层中使用完整的对象。但是我不知道加载它们的最佳方法是什么。这个问题可能看起来很愚蠢——也许确实如此——但我对此感到非常困惑。我有以下课程(只是为了说明):
public class Library
{
int ID {get;set;}
string Name {get;set;}
Book[] Novels {get;set;}
Book[] TextBooks {get;set;}
}
public class Book
{
int ID {get;set;}
Library[] SalePoints {get;set;}
string Name {get;set;}
string Type {get;set;}
}
我有两个服务方法 LoadLibrary 和 LoadBook,其目的是填充这些各自的模型。我的问题是看起来我会陷入无限循环。我现在就解释一下。
我已经预加载了来自存储库的域模型(存储库使用 valueinjecter(unflatenning)将数据模型转换为域模型,因此基本上简单的字段(int、string 等)填充在结果中域模型,但 IEnumerable 属性不是。这就是为什么我要在服务层中加载它们。(还有两个原因为什么我不能将它们完全加载到我的存储库中:1/我使用的是通用存储库和2/业务规则的加载逻辑中继)
假设我做了以下事情:
public class LibrairiesProcessor
{
public Library LoadLibrairyObject(int ID)
{
Library l = UnitOfWork.LibraryRepo.GetByID(ID); // Only retrieve "simple" properties, here it will get the Name and the ID properties;
l.Novels = UnitOfWork.BookRepo.Get(b=>b.LibrairyID==l.ID && b.Type="Novel");
l.TextBooks= UnitOfWork.BookRepo.Get(b=>b.LibrairyID==l.ID && b.Type="TextBook");
for(int i=0;i<l.Novels.Count();i++)
{
l.Novels[i] = BooksProcessor.LoadBookObject(l.Novels[i].ID);
}
}
}
和
public class BooksProcessor
{
public Book LoadBookObject(int ID)
{
Book b = UnitOfWork.LibraryRepo.GetByID(ID); // Only retrieve "simple" properties, here it will get the Name and the ID properties;
b.SalesPoint = // Get From repo using the Unit of work
for(int i=0;i<b.SalesPoint.Count();i++)
{
b.SalesPoint[i] = LibrairyProcessor.LoadLibraryObject(b.SalesPoint[i].ID);
}
}
}
没有无限循环吗? LoadLibraryObject() 调用 LoadBookObject() ,反之亦然......尤其是当你看到这本书的 SalePoint 是触发 LoadBookObject() 的图书馆时......最多同样的工作被做了两次,但我真的怀疑它会永远不会结束。
所以我想知道我是否做对了。我的目标是拥有完全加载的对象,以避免在使用之前怀疑对象是否已足够加载,但我不确定我想出的解决方案。你通常是怎么做到的?
这看起来像一个微不足道的问题,但我真的不知道如何加载我的东西。我觉得我进退两难了:
1/ 使用UnitOfWork.Repository手动填充所有属性和子属性,但是我会有很多代码和很多冗余代码。
2/ 使用部分加载的域模型,其中一些属性设置为 null,但我真的不希望这样。而且由于我的域模型很复杂,因此我没有直接使用 EF 对象,因此我不能使用它们的延迟加载。
3/从一个 LoadObjectMethod 到另一个调用 Service LoadObject 方法,以避免代码冗余,但看起来我引入了很多递归性。
我应该如何处理?
谢谢!
【问题讨论】:
标签: asp.net-mvc domain-driven-design repository-pattern n-tier-architecture ddd-repositories