自己动手搭建经典的3层 Asp.Net MVC

1:IBaseDAL

using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace C01.ZRF.IDAL
{
    public interface IBaseDAL<T> where T : class
    {

        int SaveChanges();

        void Add(T model);

        void Delete(T model);

        void DeleteBy(System.Linq.Expressions.Expression<Func<T, bool>> delWhere);

        void Modify(T model, params string[] propertyNames);

        IQueryable<T> Where(Expression<Func<T, bool>> whereLambda);

        IQueryable<T> WhereOrder<TKey>(Expression<Func<T, bool>> whereLambda, Expression<Func<T, TKey>> keySelector, bool isAsc = true);

        IQueryable<T> WhereInclude(Expression<Func<T, bool>> whereLambda, params string[] includePropertyNames);

        IQueryable<T> WhereInclude<TKey>(Expression<Func<T, bool>> whereLambda, Expression<Func<T, TKey>> keySelector, bool isAsc = true, params string[] includePropertyNames);

        IEnumerable<T> WherePaged<TKey>(int PageIndex, int PageSize, out int totalCount, Expression<Func<T, bool>> whereLambda, Expression<Func<T, TKey>> keySelector, bool isAsc = true, params string[] includePropertyNames);

        IQueryable<T> QueryBySql(string sql, params System.Data.SqlClient.SqlParameter[] ps);
    }
}

T4模板生成的接口

<#@ template language="C#" debug="false" hostspecific="true"#>
<#@ include file="EF.Utility.CS.ttinclude"#>
<#@ output extension=".cs"#>
<#
CodeGenerationTools code = new CodeGenerationTools(this);
MetadataLoader loader = new MetadataLoader(this);
CodeRegion region = new CodeRegion(this, 1);
MetadataTools ef = new MetadataTools(this); 
string inputFile1 = @"E:\Temp\test01\3LaySolution\C10.ZRF.Model\Model1.edmx";  
EdmItemCollection ItemCollection1 = loader.CreateEdmItemCollection(inputFile1); 
string namespaceName = code.VsNamespaceSuggestion(); 
EntityFrameworkTemplateFileManager fileManager = EntityFrameworkTemplateFileManager.Create(this);
#>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using C10.ZRF.Model;

namespace C01.ZRF.IDAL
{ 
<# 
foreach (EntityType entity in ItemCollection1.GetItems<EntityType>().OrderBy(e => e.Name))
{
#>
    public partial interface I<#=entity.Name#>_DAL : IBaseDAL<<#=entity.Name#>>{ }        
<#}#> 
}

生成后的效果如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using C10.ZRF.Model;

namespace C01.ZRF.IDAL

    public partial interface IBuyCar_DAL : IBaseDAL<BuyCar>{ }        
    public partial interface IMenu_DAL : IBaseDAL<Menu>{ }        
    public partial interface IProduct_DAL : IBaseDAL<Product>{ }        
    public partial interface IRole_DAL : IBaseDAL<Role>{ }        
    public partial interface IroleMenu_DAL : IBaseDAL<roleMenu>{ }        
    public partial interface IuerRole_DAL : IBaseDAL<uerRole>{ }        
    public partial interface IUser_DAL : IBaseDAL<User>{ }        
 
}

2:DAL

using System;
using System.Collections.Generic;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Linq.Expressions;

namespace C01.ZRF.DAL
{
    using C01.ZRF.IDAL;
    using IOC;
    using System.Data.Entity;

    public class BaseDAL<T>:IBaseDAL<T> where T:class
    {
        //1.创建EF上下文
        //  BaseDBContext db = new BaseDBContext();
        DbContext db = DBContextFactory.GetDbContext();

        #region 0.0 批量更新EF容器数据到数据库 +int SaveChanges()
        /// <summary>
        /// 0.0 批量更新EF容器数据到数据库
        /// </summary>
        /// <returns>返回受影响行数</returns>
        public int SaveChanges()
        {
            return db.SaveChanges();
        }
        #endregion

        #region 1.0 新增方法 +void Add(T model)
        /// <summary>
        /// 1.0 新增方法
        /// </summary>
        /// <param name="model"></param>
        public void Add(T model)
        {
            //1.直接通过EF上下文的 Set方法 获取一个 针对于 T类 做操作的 DbSet对象
            //var dbSet = db.Set<T>();
            //dbSet.Add(model);
            db.Set<T>().Add(model);
        }
        #endregion

        #region 2.0 删除方法 +void Delete(T model)
        /// <summary>
        /// 2.0 删除方法
        /// </summary>
        /// <param name="model"></param>
        public void Delete(T model)
        {
            DbEntityEntry entry = db.Entry<T>(model);
            entry.State = System.Data.Entity.EntityState.Deleted;
        }
        #endregion

        #region 2.1 条件删除方法 +void DeleteBy(System.Linq.Expressions.Expression<Func<T, bool>> delWhere)
        /// <summary>
        /// 2.1 条件删除方法
        /// </summary>
        /// <param name="delWhere">要删除的元素查询条件</param>
        public void DeleteBy(System.Linq.Expressions.Expression<Func<T, bool>> delWhere)
        {
            var delList = db.Set<T>().Where(delWhere);
            foreach (T model in delList)
            {
                Delete(model);
            }
        }
        #endregion

        #region 3.0 修改实体 + void Modify(T model, params string[] propertyNames)
        /// <summary>
        /// 3.0 修改实体
        /// </summary>
        /// <param name="model"></param>
        /// <param name="propertyNames"></param>
        public void Modify(T model, params string[] propertyNames)
        {
            DbEntityEntry entry = db.Entry<T>(model);
            entry.State = System.Data.Entity.EntityState.Unchanged;
            foreach (string proName in propertyNames)
            {
                entry.Property(proName).IsModified = true;
            }
        }
        #endregion

        #region 4.0 查询方法 +IQueryable<T> Where(Expression<Func<T, bool>> whereLambda)
        /// <summary>
        /// 4.0 查询方法
        /// </summary>
        /// <param name="whereLambda"></param>
        /// <returns></returns>
        public IQueryable<T> Where(Expression<Func<T, bool>> whereLambda)
        {
            return db.Set<T>().Where(whereLambda);
        }
        #endregion

        #region 4.1 查询方法 -带排序 +IQueryable<T> WhereOrder<TKey>
        /// <summary>
        /// 4.1 查询方法 -带排序
        /// </summary>
        /// <typeparam name="TKey"></typeparam>
        /// <param name="whereLambda"></param>
        /// <param name="keySelector">u=></param>
        /// <param name="isAsc"></param>
        /// <returns></returns>
        public IQueryable<T> WhereOrder<TKey>(Expression<Func<T, bool>> whereLambda, Expression<Func<T, TKey>> keySelector, bool isAsc = true)
        {
            if (isAsc)
                return db.Set<T>().Where(whereLambda).OrderBy(keySelector);
            else
                return db.Set<T>().Where(whereLambda).OrderByDescending(keySelector);
        }
        #endregion

        #region 4.2 查询方法 -带Include +IQueryable<T> WhereInclude
        /// <summary>
        /// 4.2 查询方法 -带Include
        /// </summary>
        /// <param name="whereLambda"></param>
        /// <param name="includePropertyNames">要进行连接查询的 属性名</param>
        /// <returns></returns>
        public IQueryable<T> WhereInclude(Expression<Func<T, bool>> whereLambda, params string[] includePropertyNames)
        {
            DbQuery<T> dbQuery = db.Set<T>();
            foreach (string includeName in includePropertyNames)
            {
                dbQuery = dbQuery.Include(includeName);
            }
            return dbQuery.Where(whereLambda);

            //DbQuery<T> dbSet = (DbQuery<T>)db.Set<T>().Where(whereLambda);
            //foreach (string includeName in includePropertyNames)
            //{
            //        dbSet = dbSet.Include(includeName);
            //}
            //return dbSet;
        }
        #endregion

        #region 4.3 查询方法 -带Include 和 排序 +IQueryable<T> WhereInclude<TKey>
        /// <summary>
        /// 4.3 查询方法 -带Include 和 排序
        /// </summary>
        /// <typeparam name="TKey"></typeparam>
        /// <param name="whereLambda"></param>
        /// <param name="keySelector"></param>
        /// <param name="isAsc"></param>
        /// <param name="includePropertyNames"></param>
        /// <returns></returns>
        public IQueryable<T> WhereInclude<TKey>(Expression<Func<T, bool>> whereLambda, Expression<Func<T, TKey>> keySelector, bool isAsc = true, params string[] includePropertyNames)
        {
            DbQuery<T> dbQuery = db.Set<T>();
            if (includePropertyNames != null && includePropertyNames.Length > 0)
            {
                foreach (string includeName in includePropertyNames)
                {
                    dbQuery = dbQuery.Include(includeName);
                }
            }
            IQueryable<T> query = dbQuery.Where(whereLambda);
            if (isAsc)
                return query.OrderBy(keySelector);
            else
                return query.OrderByDescending(keySelector);
        }
        #endregion

        #region 4.4 查询方法 - 分页+Include+排序 + void WherePaged<TKey>
        /// <summary>
        /// 4.4 查询方法 - 分页+Include+排序
        /// </summary>
        /// <typeparam name="TKey"></typeparam>
        /// <param name="pagedData"></param>
        /// <param name="whereLambda"></param>
        /// <param name="keySelector"></param>
        /// <param name="isAsc"></param>
        /// <param name="includePropertyNames"></param>
        public IEnumerable<T> WherePaged<TKey>(int PageIndex, int PageSize, out int totalCount, Expression<Func<T, bool>> whereLambda, Expression<Func<T, TKey>> keySelector, bool isAsc = true, params string[] includePropertyNames)
        {
            //0.获取 要操作的 数据表 对应的查询对象
            DbQuery<T> dbQuery = db.Set<T>();
            if (includePropertyNames != null && includePropertyNames.Length > 0)
            {
                foreach (string includeName in includePropertyNames)
                {
                    dbQuery = dbQuery.Include(includeName);
                }
            }

            IOrderedQueryable<T> orderQuery = null;
            //2.排序
            if (isAsc) { orderQuery = dbQuery.OrderBy(keySelector); }
            else { orderQuery = dbQuery.OrderByDescending(keySelector); }
            //3.分页查询
            var list = orderQuery.Where(whereLambda).Skip((PageIndex - 1) * PageSize).Take(PageSize).ToList();
            //4.获取总行数
            totalCount = orderQuery.Where(whereLambda).Count();
            return list;
        }
        #endregion

        #region 4.5 查询方法  QueryBySql(string sql, params System.Data.SqlClient.SqlParameter[] ps) SQl语句的查询方法
        public IQueryable<T> QueryBySql(string sql, params System.Data.SqlClient.SqlParameter[] ps)
        {
            return db.Database.SqlQuery<T>(sql, ps).AsQueryable();
        }
        #endregion
    }
}

T4模板生成的代码如下:

<#@ template language="C#" debug="false" hostspecific="true"#>
<#@ include file="EF.Utility.CS.ttinclude"#>
<#@ output extension=".cs"#>
<#
CodeGenerationTools code = new CodeGenerationTools(this);
MetadataLoader loader = new MetadataLoader(this);
CodeRegion region = new CodeRegion(this, 1);
MetadataTools ef = new MetadataTools(this); 
string inputFile1 = @"E:\Temp\test01\3LaySolution\C10.ZRF.Model\Model1.edmx";  
EdmItemCollection ItemCollection1 = loader.CreateEdmItemCollection(inputFile1); 
string namespaceName = code.VsNamespaceSuggestion(); 
EntityFrameworkTemplateFileManager fileManager = EntityFrameworkTemplateFileManager.Create(this);
#>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using C01.ZRF.IDAL;
using C10.ZRF.Model;

namespace C01.ZRF.DAL
{ 
<# 
foreach (EntityType entity in ItemCollection1.GetItems<EntityType>().OrderBy(e => e.Name))
{
#>
    public partial class <#=entity.Name#>_DAL : BaseDAL<<#=entity.Name#>>,I<#=entity.Name#>_DAL{ }        
<#}#> 
}

如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using C01.ZRF.IDAL;
using C10.ZRF.Model;

namespace C01.ZRF.DAL

    public partial class BuyCar_DAL : BaseDAL<BuyCar>,IBuyCar_DAL{ }        
    public partial class Menu_DAL : BaseDAL<Menu>,IMenu_DAL{ }        
    public partial class Product_DAL : BaseDAL<Product>,IProduct_DAL{ }        
    public partial class Role_DAL : BaseDAL<Role>,IRole_DAL{ }        
    public partial class roleMenu_DAL : BaseDAL<roleMenu>,IroleMenu_DAL{ }        
    public partial class uerRole_DAL : BaseDAL<uerRole>,IuerRole_DAL{ }        
    public partial class User_DAL : BaseDAL<User>,IUser_DAL{ }        
 
}

3:IBLL

using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace C01.ZRF.IBLL
{
  public  interface IBaseBLL<T>where T:class
    {
        int SaveChanges();

        void Add(T model);

        void Delete(T model);

        void DeleteBy(Expression<Func<T, bool>> delWhere);

        void Modify(T model, params string[] propertyNames);

        IQueryable<T> Where(Expression<Func<T, bool>> whereLambda);

        IQueryable<T> WhereOrder<TKey>(Expression<Func<T, bool>> whereLambda, Expression<Func<T, TKey>> keySelector, bool isAsc = true);

        IQueryable<T> WhereInclude(Expression<Func<T, bool>> whereLambda, params string[] includePropertyNames);

        IQueryable<T> WhereInclude<TKey>(Expression<Func<T, bool>> whereLambda, Expression<Func<T, TKey>> keySelector, bool isAsc = true, params string[] includePropertyNames);

        IEnumerable<T> WherePaged<TKey>(int PageIndex, int PageSize, out int totalCount, Expression<Func<T, bool>> whereLambda, Expression<Func<T, TKey>> keySelector, bool isAsc = true, params string[] includePropertyNames);

        IQueryable<T> QueryBySql(string sql, params System.Data.SqlClient.SqlParameter[] ps);
    }
}

T4代码生成器:

<#@ template language="C#" debug="false" hostspecific="true"#>
<#@ include file="EF.Utility.CS.ttinclude"#>
<#@ output extension=".cs"#>
<#
CodeGenerationTools code = new CodeGenerationTools(this);
MetadataLoader loader = new MetadataLoader(this);
CodeRegion region = new CodeRegion(this, 1);
MetadataTools ef = new MetadataTools(this); 
string inputFile1 = @"E:\Temp\test01\3LaySolution\C10.ZRF.Model\Model1.edmx";  
EdmItemCollection ItemCollection1 = loader.CreateEdmItemCollection(inputFile1); 
string namespaceName = code.VsNamespaceSuggestion(); 
EntityFrameworkTemplateFileManager fileManager = EntityFrameworkTemplateFileManager.Create(this);
#>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using C10.ZRF.Model;

namespace C01.ZRF.IBLL

<# 
foreach (EntityType entity in ItemCollection1.GetItems<EntityType>().OrderBy(e => e.Name))
{
#>
    public partial interface I<#=entity.Name#>_BLL : IBaseBLL<<#=entity.Name#>>{ }        
<#}#> 
}

效果如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using C10.ZRF.Model;

namespace C01.ZRF.IBLL
{ 
    public partial interface IBuyCar_BLL : IBaseBLL<BuyCar>{ }        
    public partial interface IMenu_BLL : IBaseBLL<Menu>{ }        
    public partial interface IProduct_BLL : IBaseBLL<Product>{ }        
    public partial interface IRole_BLL : IBaseBLL<Role>{ }        
    public partial interface IroleMenu_BLL : IBaseBLL<roleMenu>{ }        
    public partial interface IuerRole_BLL : IBaseBLL<uerRole>{ }        
    public partial interface IUser_BLL : IBaseBLL<User>{ }        
 
}

4:BLL

using System;
using System.Collections.Generic;
using System.Linq;

namespace C01.ZRF.BLL
{
    using C01.ZRF.IBLL;
    using C01.ZRF.IDAL;
    using System.Data.SqlClient;
    public partial class BaseBLL<T> : IBaseBLL<T> where T : class
    {
        protected IBaseDAL<T> basedal;
        public void Add(T model)
        {
            basedal.Add(model);
        }

        public void Delete(T model)
        {
            basedal.Delete(model);
        }

        public void DeleteBy(System.Linq.Expressions.Expression<Func<T, bool>> delWhere)
        {
            basedal.DeleteBy(delWhere);
        }

        public void Modify(T model, params string[] propertyNames)
        {
            basedal.Modify(model, propertyNames);
        }

        public IQueryable<T> QueryBySql(string sql, params SqlParameter[] ps)
        {
            return basedal.QueryBySql(sql, ps);
        }

        public int SaveChanges()
        {
            return basedal.SaveChanges();
        }

        public IQueryable<T> Where(System.Linq.Expressions.Expression<Func<T, bool>> whereLambda)
        {
            return basedal.Where(whereLambda);
        }

        public IQueryable<T> WhereInclude(System.Linq.Expressions.Expression<Func<T, bool>> whereLambda, params string[] includePropertyNames)
        {
            return basedal.WhereInclude(whereLambda, includePropertyNames);
        }

        public IQueryable<T> WhereInclude<TKey>(System.Linq.Expressions.Expression<Func<T, bool>> whereLambda, System.Linq.Expressions.Expression<Func<T, TKey>> keySelector, bool isAsc = true, params string[] includePropertyNames)
        {
            return basedal.WhereInclude<TKey>(whereLambda, keySelector, isAsc, includePropertyNames);
        }

        public IQueryable<T> WhereOrder<TKey>(System.Linq.Expressions.Expression<Func<T, bool>> whereLambda, System.Linq.Expressions.Expression<Func<T, TKey>> keySelector, bool isAsc = true)
        {
            return basedal.WhereOrder<TKey>(whereLambda, keySelector, isAsc);
        }

        public IEnumerable<T> WherePaged<TKey>(int PageIndex, int PageSize, out int totalCount, System.Linq.Expressions.Expression<Func<T, bool>> whereLambda, System.Linq.Expressions.Expression<Func<T, TKey>> keySelector, bool isAsc = true, params string[] includePropertyNames)
        {
            return basedal.WherePaged<TKey>(PageIndex, PageSize, out totalCount, whereLambda, keySelector, isAsc, includePropertyNames);
        }
    }
}

T4模板生成器:

<#@ template language="C#" debug="false" hostspecific="true"#>
<#@ include file="EF.Utility.CS.ttinclude"#>
<#@ output extension=".cs"#>
<#
CodeGenerationTools code = new CodeGenerationTools(this);
MetadataLoader loader = new MetadataLoader(this);
CodeRegion region = new CodeRegion(this, 1);
MetadataTools ef = new MetadataTools(this); 
string inputFile1 = @"E:\Temp\test01\3LaySolution\C10.ZRF.Model\Model1.edmx";  
EdmItemCollection ItemCollection1 = loader.CreateEdmItemCollection(inputFile1); 
string namespaceName = code.VsNamespaceSuggestion(); 
EntityFrameworkTemplateFileManager fileManager = EntityFrameworkTemplateFileManager.Create(this);
#>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using C10.ZRF.Model;
using C01.ZRF.IBLL;
using C01.ZRF.IDAL;
namespace C01.ZRF.BLL
{ 
<# 
foreach (EntityType entity in ItemCollection1.GetItems<EntityType>().OrderBy(e => e.Name))
{
#>
    public partial class <#=entity.Name#>_BLL : BaseBLL<<#=entity.Name#>>,I<#=entity.Name#>_BLL{ 
        I<#=entity.Name#>_DAL dal;
        public <#=entity.Name#>_BLL(I<#=entity.Name#>_DAL dal){
            this.dal=dal; base.basedal=dal;
        }
    }        
<#}#> 
}

效果如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace C01.ZRF.BLL
{
    using C10.ZRF.Model;
    using C01.ZRF.IBLL;
    using C01.ZRF.IDAL;
    public partial class RoleBLL : BaseBLL<Role>, IRole_BLL
    {
        IRole_DAL dal;
        public RoleBLL(IRole_DAL dal) {
            this.dal = dal;
            base.basedal = dal;
        }
    }
}

5:AutoFac配置文件内容

using Autofac;
using Autofac.Integration.Mvc;
using System.Reflection;

namespace WebApplication1
{
    public class AutoFacConfig
    {
        public static void Register()
        {
            //1.0 创建一个autofac的容器创建者对象
            var builder = new ContainerBuilder();

            //2.0 告诉autofac控制器类所存储的程序集是谁
            Assembly controllerAss = Assembly.Load("WebApplication1");
            builder.RegisterControllers(controllerAss);


            //3.0 将仓储层中的所有的类实例化以其接口的形式存储起来
            Assembly dalAss = Assembly.Load("C01.ZRF.DAL");
            builder.RegisterTypes(dalAss.GetTypes()).AsImplementedInterfaces();

            //4.0 将业务逻辑层中的所有的类实例化以其接口的形式存储起来
            Assembly bllAss = Assembly.Load("C01.ZRF.BLL");
            builder.RegisterTypes(bllAss.GetTypes()).AsImplementedInterfaces();

            //5.0 告诉MVC底层控制器的对象创建工作被autofac替代
            //5.0.1 创建一个真正的autofac工作容器
            var c = builder.Build();

            //5.0.2 将auto发出工作容器替换MVC底层
            System.Web.Mvc.DependencyResolver.SetResolver(new AutofacDependencyResolver(c));
        }
    }
}

配置后再去Global.asax 全局文件里面注册即可:

protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
AutoFacConfig.Register();//------

}

6:Web端来调用:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;

namespace WebApplication1.Controllers
{
    using C01.ZRF.IBLL;
    using C10.ZRF.Model.ModelView;
    using COMMOM;
    using C10.ZRF.Model.Filter;
    using System.Threading.Tasks;
    using C10.ZRF.Model;

    // [WebApplication1._Filters.ZrfComparess]
    public class HomeController : Controller
    {
        public ActionResult DoCombresTest() {
            return View();
        }

        #region MyRegion
        IBuyCar_BLL bll;
        public HomeController(IBuyCar_BLL bll)
        {
            this.bll = bll;
        }
        // GET: Home
        public ActionResult Index()
        {
            ViewBag.car = bll.Where(c => c.cid == 6).FirstOrDefault().pcount;
            ViewBag.time = "时间是=" + DateTime.Now.ToString();
            return View();
        }
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值