ASP.NET MVC5框架搭建3SP--Autofac多DBContext整合

本文详细阐述了如何在ASP.NET MVC5项目中使用Autofac进行多数据库上下文(DbContext)的管理。通过修改Model、Repository、Service和Web项目的代码,实现了针对不同数据源的Repository接口和Service接口。在Web项目的Autofac配置中,完成了DBContext的注册,以确保正确连接和操作多个数据库。
摘要由CSDN通过智能技术生成

本文介绍了如何使用Autofac连接管理多个数据库。

Model项目修改

首先根据前文提到的方法再次添加一个数据源,别忘记web.congfig的修改。

Repository项目修改

打开Repository/BaseRepository文件,进行代码改写:

using System;
using System.Data.Entity;
using System.Linq;
using System.Linq.Expressions;

namespace MVC5Demo.Repository.Repository
{
   
    public class BaseRepository<T> : IRepository.IBaseRepository<T> where T : class
    {
   
        protected DbContext _dbContext;
        protected DbSet<T> _dbSet;

        public IQueryable<T> Find(Expression<Func<T, bool>> exp = null)
        {
   
            if (exp == null) return _dbSet;
            return _dbSet.Where(exp);
        }
    }
}

在IRepository新建接口文件IDemoDBRepository和IDemoDB2Repository,并继承IBaseRepository接口,代码如下:

namespace MVC5Demo.Repository.IRepository
{
   
    public interface IDemoDBRepository<T> : IBaseRepository<T> where T : class
    {
   
    }
}
namespace MVC5Demo.Repository.IRepository
{
   
    public interface IDemoDB2Repository<T> 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值