如何将dbcontext映射到实际的dbcontext [英] How to mapped dbcontext to actual dbcontext

查看:111
本文介绍了如何将dbcontext映射到实际的dbcontext的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建通用存储库和通用工作单元。当我尝试保存记录但遗憾的是记录未保存甚至没有错误发生。



我尝试过:



公共接口IRepository< TEntity>其中TEntity:class,new()
{
任务< IReadOnlyList< TEntity>> ListAllAsync();
任务AddAsync(TEntity实体);
}





公共类存储库< T> :IRepository< T>其中T:class,new()
{
protected readonly DbContext _dbContext;
public Repository(DbContext dbContext)
{
this._dbContext = dbContext;
}

public async任务AddAsync(T entity)
{
await _dbContext.Set< T>()。AddAsync(entity);
}

公共异步任务< IReadOnlyList< T>> ListAllAsync()
{
返回await _dbContext.Set< T>()。AsNoTracking()。ToListAsync();
}
}



公共接口IUnitOfWork:IDisposable 
{
任务CompleteAsync();
}



公共类UnitOfWork:IUnitOfWork 
{
private readonly DbContext _dbContext;
public UnitOfWork(DbContext dbContext)
{
_dbContext = dbContext;
}
public async Task CompleteAsync()
{
await _dbContext.SaveChangesAsync();
}

public void Dispose()
{
_dbContext.Dispose();
}
}



公共类CustomerService:ICustomerService 
{
private readonly IRepository< Customer> ; _customerRepository;
private readonly IUnitOfWork _unitOfWork;
public CustomerService(IRepository< Customer> customerRepository,IUnitOfWork unitOfWork)
{
this._customerRepository = customerRepository;
this._unitOfWork = unitOfWork;
}
public async任务< IEnumerable< CustomerList>> ListAsync()
{
var customer = await _customerRepository.ListAllAsync();
列表< CustomerList> customers = new List< CustomerList>();
foreach(客户中的var项目)
{
customers.Add(new CustomerList {Id = item.Id,Name = item.Name});
}
退货客户;
}

公共异步任务< CustomerResource> SaveAsync(CustomerResource category)
{

try
{
await _customerRepository.AddAsync(new Customer {Name = category.Name});
await _unitOfWork.CompleteAsync();
返回新的CustomerResource(true,Successfully);
}
catch(exception ex)
{

返回新的CustomerResource($保存客户时发生错误:{ex.Message});
}

}
}



 services.AddScoped< DbContext,ApplicationDbContext>() ; 



 services.AddScoped< IUnitOfWork,UnitOfWork>(); 
services.AddScoped(typeof(IRepository<>),typeof(Repository<>));

解决方案

保存客户时出错:{ex.Message});
}

}
}



 services.AddScoped< DbContext,ApplicationDbContext>() ; 



 services.AddScoped< IUnitOfWork,UnitOfWork>(); 
services.AddScoped(typeof(IRepository<>),typeof(Repository<>));


您不发布您的ApplicationDbContext或者你的conenction字符串是如何提供的,但是可以扩展DbContext,因此:



公共类ApplicationDbContext:DbContext 
{
public ApplicationDbContext(DbContextOptions< CrmContext> options):base(options)
{

}

//此处剩余代码...
}







您的工作单位应该收到您的ApplicationDbContext:



公共类UnitOfWork:IUnitOfWork 
{
private readonly ApplicationDbContext_dbContext;
public UnitOfWork(ApplicationDbContext dbContext)
{
_dbContext = dbContext;
}
public async Task CompleteAsync()
{
await _dbContext.SaveChangesAsync();
}

public void Dispose()
{
_dbContext.Dispose();
}
}





然后你可以将连接字符串作为依赖注入的一部分传递:



 services.AddDbContext< ApplicationDbContext>((options => options.UseSqlServer([连接字符串详细信息转到此处])); 


I am creating generic Repositories and generic Unit of work .when i am trying to save record but unfortunately record is not saved and even no error is occur.

What I have tried:

public interface IRepository<TEntity> where TEntity : class,new()
    {
        Task<IReadOnlyList<TEntity>> ListAllAsync();
        Task AddAsync(TEntity entity);
    }



public class Repository<T> : IRepository<T> where T : class, new()
   {
       protected readonly DbContext _dbContext;
       public Repository(DbContext dbContext)
       {
           this._dbContext = dbContext;
       }

       public async Task AddAsync(T entity)
       {
           await _dbContext.Set<T>().AddAsync(entity);
       }

       public async Task<IReadOnlyList<T>> ListAllAsync()
       {
           return await _dbContext.Set<T>().AsNoTracking().ToListAsync();
       }
   }


public interface IUnitOfWork : IDisposable
    {
        Task CompleteAsync();
    }


public class UnitOfWork : IUnitOfWork
    {
        private readonly DbContext _dbContext;
        public UnitOfWork(DbContext dbContext)
        {
            _dbContext = dbContext;
        }
        public async Task CompleteAsync()
        {
           await _dbContext.SaveChangesAsync();
        }

        public void Dispose()
        {
            _dbContext.Dispose();
        }
    }


public class CustomerService : ICustomerService
    {
        private readonly IRepository<Customer> _customerRepository;
        private readonly IUnitOfWork _unitOfWork;
        public CustomerService(IRepository<Customer> customerRepository, IUnitOfWork unitOfWork)
        {
            this._customerRepository = customerRepository;
            this._unitOfWork = unitOfWork;
        }
        public async Task<IEnumerable<CustomerList>> ListAsync()
        {
            var customer = await _customerRepository.ListAllAsync();
            List<CustomerList> customers = new List<CustomerList>();
            foreach (var item in customer)
            {
                customers.Add(new CustomerList { Id = item.Id, Name = item.Name });
            }
            return customers;
        }

        public async Task<CustomerResource> SaveAsync(CustomerResource category)
        {
            
            try
            {
                await _customerRepository.AddAsync(new Customer { Name = category.Name });
                await _unitOfWork.CompleteAsync();
               return new CustomerResource(true, "Successfully");
            }
            catch (Exception ex)
            {

              return  new CustomerResource($"An error occurred when saving the customer :{ex.Message}" );
            }

        }
    }


services.AddScoped<DbContext, ApplicationDbContext>();


services.AddScoped<IUnitOfWork, UnitOfWork>();
            services.AddScoped(typeof(IRepository<>), typeof(Repository<>));

解决方案

"An error occurred when saving the customer :{ex.Message}" ); } } }


services.AddScoped<DbContext, ApplicationDbContext>();


services.AddScoped<IUnitOfWork, UnitOfWork>();
            services.AddScoped(typeof(IRepository<>), typeof(Repository<>));


You don't post your ApplicationDbContext, or how your conenction string is provided, but pottentially ApplicationDbContext should extend DbContext, so:

public class ApplicationDbContext: DbContext
    {
        public ApplicationDbContext(DbContextOptions<CrmContext> options) : base(options)
        {
            
        }

// Remaining code here...
    }




And your Unit of Work should receive your ApplicationDbContext:

public class UnitOfWork : IUnitOfWork
    {
        private readonly ApplicationDbContext_dbContext;
        public UnitOfWork(ApplicationDbContext dbContext)
        {
            _dbContext = dbContext;
        }
        public async Task CompleteAsync()
        {
           await _dbContext.SaveChangesAsync();
        }

        public void Dispose()
        {
            _dbContext.Dispose();
        }
    }



And then you can pass your connection string as part of the dependency injection:

services.AddDbContext<ApplicationDbContext>((options => options.UseSqlServer([connection string details go here]));


这篇关于如何将dbcontext映射到实际的dbcontext的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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