【问题标题】:Where should I do the mapping stuff? Repository or Service Layer?我应该在哪里做映射的东西?存储库还是服务层?
【发布时间】:2017-02-02 11:04:44
【问题描述】:

嗯,我有这个数据库模型“书”

public class Book {
    public int Id { get; set; }
    public string Title { get; set; }
    public string Author { get; set; }
    public bool IsSubmitted { get; set; }
    public bool IsCompleted { get; set; }
    public bool IsDeleted { get; set; }
}    

我已经实现了存储库模式,其中我的GetBook(int id) 方法返回一个Book,如下所示:

public Book GetBook(int id) {
    return db.Books.Find(id);
}

不过,我的BookViewModel 还需要查询一些其他的东西。它看起来像这样:

public class BookViewModel
{
    public int Id { get; set; }
    public string Title { get; set; }
    public string AuthorName { get; set; }
    public int CommentsCount { get; set; }
    public int FeedbacksCount { get; set; }
    public int ViewsCount { get; set; }
}

目前,我的服务层正在将绑定模型映射到数据库模型并将它们传递到存储库。 现在我的问题是我应该在哪里查询这些额外的(特定于视图的)数据?我应该为CommentsCount, FeedbacksCount, ViewsCount 等编写单独的存储库方法并从我的服务层调用它们以准备我的视图模型,还是应该编写一个返回类型为BookViewModel 的新存储库方法,在其中我在单个查询中查询所有必需的数据?

非常感谢任何帮助。

【问题讨论】:

    标签: entity-framework asp.net-web-api repository-pattern service-layer


    【解决方案1】:

    存储库方法应该映射并返回或接收 DTO,DAL 层不应该知道 MVC 项目,它应该只知道 DTO。

    【讨论】:

    • 在这种情况下,我应该使用以前的解决方案,一次又一次地查询数据库以获取 CommentsCount、FeedbacksCount 等?我的意思是在大量数据的情况下它不会效率低下吗?没有办法解决这个问题吗?
    • 在您的存储库中,您应该有一个像 GetComments 这样的方法,因此 CommentsCount 您可以在服务层调用 GetComments 方法并使用 .Count() 获得计数?您不应该真正在存储库上创建一个将为您准备 viewModel 的方法。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-25
    • 2013-11-18
    • 1970-01-01
    • 2016-10-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多