c# - N 层存储库 POCO - 聚合?

标签 c# asp.net repository-pattern poco

假设以下简单的 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 中,我不会显示所有子项(状态),但会显示总计数。所以我的国家/地区 ListView 模型可能如下所示:

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 层中使用底层数据提供程序( Entity Framework 、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();

但是当我使用存储库或服务模式时,我抽象出对数据层的直接访问。似乎我的选择是:

  1. 返回带有填充状态集合的国家/地区,然后在 UI 层中进行映射。这种方法的缺点是我返回的数据比实际需要的多得多。

    -或-

  2. 将我所有的 View 模型放入我的 Common dll 库(而不是将它们放在我的 MVC 应用程序的 Models 目录中)并扩展我的存储库以返回特定的 View 模型,而不仅仅是域 pocos。这种方法的缺点是我将 UI 特定的东西(MVC 数据验证注释)泄漏到我以前干净的 POCO 中。

    -或-

  3. 还有其他选择吗?

您如何处理这些类型的事情?

最佳答案

这实际上取决于我们所做的项目架构。但是通常......我们在存储库之上有服务为您处理这个逻辑。该服务决定使用哪些存储库来加载哪些数据。流程是 UI -> Controller -> Service -> Repositories -> DB。 UI 和/或 Controller 不知道存储库或其实现。

此外,StateCount = c.States.Count 毫无疑问无论如何都会填充州列表.. 不是吗?我很确定它会在 NHibernate 中(使用 LazyLoading 导致额外的选择被发送到数据库)。

关于c# - N 层存储库 POCO - 聚合?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12828190/

相关文章:

javascript - ASP.NET MVC 中的按钮提交

javascript - 单选按钮 asp.net 突出显示 div

c# - 依赖注入(inject)

c# - 查找列表中包含 x 或 y 的所有行?

c# - ParallelExtensions "Extras"是否仍然有值(value)?

c# - throw 后生成

c# - HttpClient-PostAsJsonAsync

c# - JavaScript:来自 ASP.NET 代码隐藏的 Alert.Show(message)

c# - MVC 存储库 - 域模型与实体模型

linq - 如果我从我的服务层公开 IQueryable,如果我需要从多个服务中获取信息,数据库调用会不会更少?