.net核心-工作单元通用存储库模式 [英] .net core - unit of work generic repository pattern

查看:98
本文介绍了.net核心-工作单元通用存储库模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一个大型项目,该项目将收集有关产品的信息。当前应用程序使用CSLA作为其框架(传统的aspx形式)。

I am Looking to migrate a large project that gathers information about products. The current application uses CSLA as its framework (traditional aspx forms).

我想将应用程序迁移/开发到.net core 2.1。我有从事MVC的经验(4年以上),并且最近接触过.net内核。

I am wanting to migrate / develop the application over to .net core 2.1. I have experience of developing in MVC (4+ years) and some recent exposure to .net core.

我想使用EF Core调用现有的存储过程。我正在研究使用工作单元通用存储库设计模式。我以前使用过存储库模式,发现它非常有用。

I am wanting to use EF Core to call the existing stored procedures. I am looking at using the Unit of Work Generic repository design pattern. I have used the repository pattern before and found it very useful.

作为当前流程中存在的功能的一部分,它包含一个Master表和一个Edits表结构格式。当某人编辑产品时,新行将插入到编辑表中。一旦获得管理员批准,它就会在主表中插入/更新当前行。

As part of the functionality that exists within the current process, it contains a Master table and an Edits table structure format. When someone edits a product, a new row is inserted into the Edits table. Once approved by an admin, it then inserts / updates the current row in the Master table.

.net core 2.1内的其他开发人员是否已使用工作单元/通用存储库模式?

Has using the ‘Unit of Work / generic repository pattern’ worked well for other developers within .net core 2.1?

您遇到了什么问题?
我的目标是生产高性能,高效率的驱动程序。

What issues have you come across? My aim is to produce a high performance efficient driven application.

其他任何想法和建议都欢迎。谢谢。

Any other thoughts and suggestions are welcome. Thanks.

推荐答案

我个人使用工作单元来减少很多依赖注入。我可以有一个数据库工作单元,一旦我使用依赖注入在该工作单元中注入数据库上下文,就不需要在要使用它们的地方注入每个模型存储库,而只需从数据库中访问存储库即可。工作单元。

Personally, i use Unit of Work to reduce a lot of dependency Injection. I can have a database Unit of work and once i use dependency Injection to inject the Database context in that Unit of work, i don't need to inject each model repository where i want to use them, but will just access the repositories from the unit of work. This also helps me only instantiate a repository only when i need it in a specific method.

public interface IDatabaseUnitOfWork
{
    DbContext DatabaseContext { get; }
    Task<bool> Save();

    IBaseRepository<UserAccount> UserAccountRepository { get; }
}

public class DatabaseUnitOfWork : IDatabaseUnitOfWork
{
    private IBaseRepository<UserAccount> _userAccountRepository;

    public DatabaseUnitOfWork(DbContext databaseContext)
    {
        DatabaseContext = databaseContext;
    }

    public DbContext DatabaseContext { get; private set; }

    public async Task<bool> Save()
    {
        try
        {
            int _save = await DatabaseContext.SaveChangesAsync();
            return await Task.FromResult(true);
        }
        catch (System.Exception e)
        {
            return await Task.FromResult(false);
        }
    }

    public IBaseRepository<UserAccount> UserAccountRepository
    {
        get
        {
            if (_userAccountRepository == null)
            {
                _userAccountRepository = new BaseRepository<UserAccount>(DatabaseContext);
            }
            return _userAccountRepository;
        }
    }
}

然后

services.AddScoped<IDatabaseUnitOfWork, DatabaseUnitOfWork>();
services.AddScoped<IServiceUnitOfWork, ServiceUnitOfWork>();

最后

public class DemoClass
    {
        private IServiceUnitOfWork _serviceUnitOfWork;
        public DemoClass(IServiceUnitOfWork serviceUnitOfWork)
        {
            _serviceUnitOfWork = serviceUnitOfWork;
        }

        Public bool CreateUserAccount(UserAccount userAccount){
            await _serviceUnitOfWork.UserAccountRepository.Add(userAccount);
            return await _serviceUnitOfWork.Save();
        }

       ----
   }

更新

基本库

public interface IBaseRepository<T> where T : class
{
    Task<bool> Add(T entity);

    Task<List<T>> GetAll();

    Task<List<T>> GetAll(params Expression<Func<T, object>>[] includes);

    Task<List<T>> SearchBy(Expression<Func<T, bool>> searchBy, params Expression<Func<T, object>>[] includes);

    Task<T> FindBy(Expression<Func<T, bool>> predicate, params Expression<Func<T, object>>[] includes);

    Task<bool> Update(T entity);

    Task<bool> Delete(Expression<Func<T, bool>> identity, params Expression<Func<T, object>>[] includes);

    Task<bool> Delete(T entity);

}

public class BaseRepository<T> : IBaseRepository<T> where T : class
{
    private DbContext _ctx;

    public BaseRepository(DbContext context)
    {
        _ctx = context;
    }

    public virtual async Task<bool> Add(T entity)
    {
        try
        {
            _ctx.Set<T>().Add(entity);
            return  await Task.FromResult(true);
        }
        catch (Exception e)
        {
            return  await Task.FromResult(false);
        }
    }

    public virtual async Task<List<T>> GetAll()
    {
        return _ctx.Set<T>().ToList();
    }

    public virtual async Task<List<T>> GetAll(params Expression<Func<T, object>>[] includes)
    {
        var result = _ctx.Set<T>().Where(i => true);

        foreach (var includeExpression in includes)
            result = result.Include(includeExpression);

        return await result.ToListAsync();
    }


    public virtual async Task<List<T>> SearchBy(Expression<Func<T, bool>> searchBy, params Expression<Func<T, object>>[] includes)
    {
        var result = _ctx.Set<T>().Where(searchBy);

        foreach (var includeExpression in includes)
            result = result.Include(includeExpression);

        return await result.ToListAsync();
    }

    /// <summary>
    /// Finds by predicate.
    /// http://appetere.com/post/passing-include-statements-into-a-repository
    /// </summary>
    /// <param name="predicate">The predicate.</param>
    /// <param name="includes">The includes.</param>
    /// <returns></returns>
    public virtual async Task<T> FindBy(Expression<Func<T, bool>> predicate, params Expression<Func<T, object>>[] includes)
    {
        var result = _ctx.Set<T>().Where(predicate);

        foreach (var includeExpression in includes)
            result = result.Include(includeExpression);

        return await result.FirstOrDefaultAsync();
    }

    public virtual async Task<bool> Update(T entity)
    {
        try
        {
            _ctx.Set<T>().Attach(entity);
            _ctx.Entry(entity).State = EntityState.Modified;

            return  await Task.FromResult(true);
        }
        catch (Exception e)
        {
            return  await Task.FromResult(false);
        }
    }

    public virtual async Task<bool> Delete(Expression<Func<T, bool>> identity, params Expression<Func<T, object>>[] includes)
    {
        var results = _ctx.Set<T>().Where(identity);

        foreach (var includeExpression in includes)
            results = results.Include(includeExpression);
        try
        {
            _ctx.Set<T>().RemoveRange(results);
            return  await Task.FromResult(true);
        }
        catch (Exception e)
        {
            return  await Task.FromResult(false);
        }
    }

    public virtual async Task<bool> Delete(T entity)
    {
        _ctx.Set<T>().Remove(entity);
        return await Task.FromResult(true);
    }

}

扩展基本存储区(例如 DeleteAllAccounts

EXTENDING THE BASE REPOSITORY (eg. DeleteAllAccounts)

public interface IUserAccountRepository : IBaseRepository<UserAccount>
    {
        Task DeleteAllAccounts();
    }

    public class UserAccountRepository : BaseRepository<UserAccount>, IUserAccountRepository
    {
        private DbContext _databaseContext;
        public UserAccountRepository(DbContext databaseContext) : base(databaseContext)
        {
            _databaseContext = databaseContext;
        }

        public async Task DeleteAllAccounts()
        {
            ......
        }
    }

所以不要使用 _userAccountRepository = new BaseRepository< UserAccount>(DatabaseContext); 您将使用 _userAccountRepository = new UserAccountRepository(DatabaseContext);

So instead of using _userAccountRepository = new BaseRepository<UserAccount>(DatabaseContext); you would use _userAccountRepository = new UserAccountRepository(DatabaseContext);

这篇关于.net核心-工作单元通用存储库模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆