编程语言
首页 > 编程语言> > c# – 如何在ASP.NET MVC中组织DAL

c# – 如何在ASP.NET MVC中组织DAL

作者:互联网

我正在尝试在asp.net mvc项目中组织数据访问层.我已经阅读了很多不同的文章,所以我仍然有一些问题要完成这个问题:

>我应该为数据库中的每个实体创建存储库实例,还是为所有或一个基本实例创建存储库实例,例如PostRepository可以包含Post,Comment和Tag等实体?
>在控制器中,我必须获取一些数据,转换为ViewModel并将其传递到视图中.这是最好的去处?服务,控制器或其他什么?
>如果是服务.我应该创建多少服务?对于每个实体,如果是必要的话,还会转入Controller 3或4服务?或者也许就像我想在存储库中这样做? (创建一个包含一些存储库计数的公共服务.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();
}

并在单个上下文类中实现上面的接口.

有些人也实现了单独的特定存储库.

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)类.服务方法返回模型实例,控制器将它们转换为viewmodel(使用AutoMapper)并传递给视图.同样在post方法控制器中,首先将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);
    }
}

标签:c,asp-net-mvc,data-access-layer
来源: https://codeday.me/bug/20190624/1275659.html