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, );
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 > )
{
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 > )
{
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 - ) * 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, );
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, );
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, );
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 == ).FirstOrDefault().pcount;
ViewBag.time = "时间是=" + DateTime.Now.ToString();
return View();
}
}
}

最新文章

  1. HTML 基础知识
  2. java 分布式锁方案
  3. linux 系统服务
  4. Leetcode Unique Paths
  5. Thinking in Java——笔记(1)
  6. CSS+HTML网页设计与布局(学习笔记1)
  7. [转]几种常见SQL分页方式
  8. html之marquee详解[转]
  9. iOS不勾选设置,实现某个界面强制横屏
  10. Visio Premium 2010钥匙+激活破解方法
  11. [.NET] 一步步打造一个简单的 MVC 电商网站 - BooksStore(四)
  12. Python day 6(5) Python 函数式编程3
  13. Tomcat服务器简单测试jsp文件和html文件
  14. hibernate学习之持久化对象
  15. 类SimpleDateFormat
  16. Promise和setTimeout执行顺序 面试题
  17. springboot启动配置原理之三(事件监听机制)
  18. dubbo 异步回调
  19. Numpy数组与PIL Image转换
  20. Codeforces 813E - Army Creation

热门文章

  1. HTTP协议中的chunked编码解析
  2. Android框架Volley使用:Json请求实现
  3. 软工个人项目(Java实现)
  4. 结对编程(Java实现)
  5. 使用 Vim 搭建 C/C++ 开发环境
  6. 9.python3实用编程技巧进阶(四)
  7. fiddler---Fiddler弱网测试
  8. 数据分析三剑客 numpy,oandas,matplotlib(2)
  9. angular 使用ng-zorro的from组件 运行报错
  10. Python进阶-XVI 继承 单继承 多继承