假设以下简单的 POCO、国家和州:
public partial class Country
{
public Country()
{
States = new List<State>();
}
public virtual int CountryId { get; set; }
public virtual string Name { get; set; }
public virtual string CountryCode { get; set; }
public virtual ICollection<State> States { get; set; }
}
public partial class State
{
public virtual int StateId { get; set; }
public virtual int CountryId { get; set; }
public virtual Country Country { get; set; }
public virtual string Name { get; set; }
public virtual string Abbreviation { get; set; }
}
现在假设我有一个看起来像这样的简单存储库:
public partial class CountryRepository : IDisposable
{
protected internal IDatabase _db;
public CountryRepository()
{
_db = new Database(System.Configuration.ConfigurationManager.AppSettings["DbConnName"]);
}
public IEnumerable<Country> GetAll()
{
return _db.Query<Country>("SELECT * FROM Countries ORDER BY Name", null);
}
public Country Get(object id)
{
return _db.SingleById(id);
}
public void Add(Country c)
{
_db.Insert(c);
}
/* ...And So On... */
}
通常在我的 UI 中,我不会显示所有子项(状态),但会显示汇总计数。所以我的国家列表视图模型可能如下所示:
public partial class CountryListVM
{
[Key]
public int CountryId { get; set; }
public string Name { get; set; }
public string CountryCode { get; set; }
public int StateCount { get; set; }
}
当我直接在我的 UI 层中使用底层数据提供程序(实体框架、NHibernate、PetaPoco 等)时,我可以轻松地执行以下操作:
IList<CountryListVM> list = db.Countries
.OrderBy(c => c.Name)
.Select(c => new CountryListVM() {
CountryId = c.CountryId,
Name = c.Name,
CountryCode = c.CountryCode,
StateCount = c.States.Count
})
.ToList();
但是当我使用存储库或服务模式时,我抽象出对数据层的直接访问。似乎我的选择是:
使用填充的 States 集合返回 Country,然后在 UI 层中映射。这种方法的缺点是我返回的数据比实际需要的多得多。
-或者-
将我所有的视图模型放入我的 Common dll 库中(而不是将它们放在我的 MVC 应用程序的 Models 目录中)并扩展我的存储库以返回特定的视图模型,而不仅仅是域 pocos。这种方法的缺点是我将 UI 特定的东西(MVC 数据验证注释)泄漏到我以前干净的 POCO 中。
-或者-
还有其他选择吗?
你是如何处理这些类型的事情的?