我正在尝试在 asp.net mvc 项目中组织数据访问层。我已经阅读了很多关于这个的不同文章,所以我仍然有一些问题来解决这个问题:
我应该为数据库中的每个实体还是为所有或一个通用实例创建存储库实例,例如 PostRepository
可以包含像 Post
、评论
和标签
?
在 Controller 中,我必须获取一些数据,将其转换为 ViewModel 并将其传递到 View 中。最好的地方在哪里? Services
、Controller
还是其他?
如果是服务
。我应该创建多少个服务?如果有必要,还为每个实体传递到 Controller 3 或 4 服务吗?或者也许像我想在存储库中那样做? (创建一个包含一些存储库的公共(public)服务。PostService
,存储库如 PostRepository
、CommentRepository
和 TagRepository
)
这是我的看法:
Should I create instances of repository for every entity in database
or for all or one genereal instance, for example PostRepository can
include entities like Post, Comment and Tag?
拥有一个单一的通用存储库将为您省去很多维护难题。您可以实现单个通用存储库,例如:
/// <summary>
/// This interface provides an abstraction for accessing a data source.
/// </summary>
public interface IDataContext : IDisposable
{
IQueryable<T> Query<T>() where T : class;
T Add<T>(T item) where T : class;
int Update<T>(T item) where T : class;
void Delete<T>(T item) where T : class;
/// <summary>
/// Allow repositories to control when SaveChanges() is called
/// </summary>
int SaveChanges();
}
并在单个上下文类中实现上述接口(interface)。
有些人也实现单独的特定存储库。
In controller I have to get some data, transform in into ViewModel and
pass it into view. Where is the best place to do this? Services,
Controller or something else?
在可从 DA、服务和 Web 访问的单独程序集中定义所有模型(DTO 或实体或 POCO)类。服务方法返回模型实例, Controller 将它们转换为 View 模型(使用 AutoMapper)并传递给 View 。同样在post method controller中,先将VM转化为Model,然后传给Service层进行持久化或处理。
If it is Service. How many services should I create? Also for every
entity and pass into Controller 3 or 4 services if it is necessery? Or
maybe do it like I wanted to do it in repository? (Create one common
service which would contain some count of repositories. PostService,
with repositories like PostRepository, CommentRepository and
TagRepository)
我强烈建议您非常具体地定义服务。使用单一职责原则来定义您的服务。每个服务都应该提供相关的功能集。例如。 AuthService 将对不向他们发送电子邮件的用户进行身份验证,即 EmailService 工作。
我建议的模式非常适合不同的服务。例如:
public class DriverSearchService : IDriverSearchService
{
private readonly IBlobService _blobService;
private readonly IDataContext _dataContext;
public DriverSearchService(IDataContext dataContext, IBlobService blobService)
{
_blobService = blobService;
_dataContext = dataContext;
}
public void SaveDriveSearch(int searchId)
{
// Fetch values from temp store and clear temp store
var item = context.Query<SearchTempStore>().Single(s => s.SearchId == searchId);
// Temp object is latest so update the main store
var mainSearch = context.Query<Search>().Single(s => s.Id == searchId);
mainSearch.LastExecutedOn = DateTime.UtcNow;
mainSearch.DataAsBlob = item.DataAsBlob;
context.Update(mainSearch);
}
}