码迷,mamicode.com
首页 > Web开发 > 详细

EF6.0+APS.NET MVC5.0项目初探四(填充各个程序集)

时间:2014-08-02 18:02:43      阅读:465      评论:0      收藏:0      [点我收藏+]

标签:des   style   blog   http   color   os   io   数据   

第一步:每次生成数据库是都需要修改的地方

在Domain.DbContext中添加

bubuko.com,布布扣

在Infrastructure.Ioc.DALFactory中添加

bubuko.com,布布扣

 

第二步:DataAccess.DAL说明:

我们先在此添加一个基类

  1 using System;
  2 using System.Collections.Generic;
  3 using System.Data;
  4 using System.Data.Entity;
  5 using System.Data.Entity.Infrastructure;
  6 using System.Linq;
  7 using System.Linq.Expressions;
  8 using System.Reflection;
  9 using System.Text;
 10 using System.Threading.Tasks;
 11 //
 12 
 13 namespace DataAccess.DAL
 14 {
 15     /// <summary>
 16     /// EF DAL CURD基类
 17     /// </summary>
 18     /// <typeparam name="T"></typeparam>
 19     public abstract class BaseDAL<T> where T : class,new()
 20     {
 21 
 22         /// <summary>
 23         /// 上下文网关
 24         /// </summary>
 25         protected Domain.DbContext.DbContext db = new Domain.DbContext.DbContext();
 26         // protected   DbContext  db = new DBContextFactory().GetDbContext();//直接从线程中获取上下文网关
 27 
 28         #region 1.Add
 29 
 30         /// <summary>
 31         /// 增加一条数据
 32         /// </summary>
 33         /// <param name="entity"></param>
 34         /// <returns></returns>
 35         public bool AddEntity(T entity)
 36         {
 37 
 38             db.Entry<T>(entity).State = System.Data.Entity.EntityState.Added;
 39             // db.Set<T>().Add(entity);此方法同上方法
 40             return db.SaveChanges() > 0;
 41         }
 42         /// <summary>
 43         /// 同时增加多条数据到一张表(事务处理)
 44         /// </summary>
 45         /// <param name="entitys"></param>
 46         /// <returns></returns>
 47         public bool AddEntity(List<T> entitys)
 48         {
 49             foreach (var entity in entitys)
 50             {
 51                 db.Entry<T>(entity).State = System.Data.Entity.EntityState.Added;
 52             }
 53             // entitys.ForEach(c=>db.Entry<T>(c).State = EntityState.Added);//等价于上面的循环
 54             return db.SaveChanges() > 0;
 55         }
 56         #endregion
 57 
 58         #region 2.Modify
 59         /// <summary>
 60         /// 修改一条数据,会修改所有列的值,没有赋值的属性将会被赋予属性类型的默认值**************
 61         /// </summary>
 62         /// <param name="entity"></param>
 63         /// <returns></returns>
 64         public bool ModifyEntity(T entity)
 65         {
 66             db.Set<T>().Attach(entity);
 67             db.Entry<T>(entity).State = System.Data.Entity.EntityState.Modified;//将所有属性标记为修改状态
 68             return db.SaveChanges() > 0;
 69         }
 70         public bool ModifyEntity(List<T> entitys)
 71         {
 72             entitys.ForEach(entity =>
 73             {
 74                 db.Set<T>().Attach(entity);
 75                 db.Entry<T>(entity).State = System.Data.Entity.EntityState.Modified;//将所有属性标记为修改状态
 76             });
 77             return db.SaveChanges() > 0;
 78         }
 79         /// <summary>
 80         /// 修改一条数据,会修改指定列的值
 81         /// </summary>
 82         /// <param name="entity">要修改的实体对象</param>
 83         /// <param name="proNames">要修改的属性名称</param>
 84         /// <returns></returns>
 85         public bool ModifyEntity(T entity, params string[] proNames)
 86         {
 87 
 88             DbEntityEntry<T> dbee = db.Entry<T>(entity);
 89             if (dbee.State == System.Data.Entity.EntityState.Detached)
 90             {
 91                 db.Set<T>().Attach(entity);
 92             }
 93             dbee.State = System.Data.Entity.EntityState.Unchanged;//先将所有属性状态标记为未修改
 94             proNames.ToList().ForEach(c => dbee.Property(c).IsModified = true);//将要修改的属性状态标记为修改
 95             return db.SaveChanges() > 0;
 96         }
 97         /// <summary>
 98         /// 根据条件批量修改指定的列********************
 99         /// </summary>
100         /// <param name="entity"></param>
101         /// <param name="whereLambds"></param>
102         /// <param name="proNames"></param>
103         /// <returns></returns>
104         public bool ModifyEntity(T entity, Expression<Func<T, bool>> whereLambds, params string[] proNames)
105         {
106             var entitys = db.Set<T>().Where(whereLambds).ToList();
107             PropertyInfo[] proinfos = entity.GetType().GetProperties();
108             List<PropertyInfo> list = new List<PropertyInfo>();
109             foreach (var p in proinfos)
110             {
111                 if (proNames.Contains(p.Name))
112                 {
113                     list.Add(p);
114                 }
115             }
116             entitys.ForEach(c =>
117             {
118                 foreach (var p in list)
119                 {
120                     object value = p.GetValue(entity, null);
121                     p.SetValue(c, value, null);
122                 }
123             });
124             return db.SaveChanges() > 0;
125         }
126         #endregion
127 
128         #region 3.Delete
129 
130         /// <summary>
131         /// 删除一个实体对象
132         /// </summary>
133         /// <param name="entity"></param>
134         /// <returns></returns>
135         public bool DeleteEntity(T entity)
136         {
137             db.Set<T>().Attach(entity);
138             db.Entry<T>(entity).State = System.Data.Entity.EntityState.Deleted;
139             return db.SaveChanges() > 0;
140         }
141         /// <summary>
142         /// 根据条件批量删除实体对象
143         /// </summary>
144         /// <param name="whereLambds"></param>
145         /// <returns></returns>
146         public bool DeleteEntityByWhere(Expression<Func<T, bool>> whereLambds)
147         {
148             var data = db.Set<T>().Where<T>(whereLambds).ToList();
149             return DeleteEntitys(data);
150         }
151         /// <summary>
152         /// 事务批量删除实体对象
153         /// </summary>
154         /// <param name="entitys"></param>
155         /// <returns></returns>
156         public bool DeleteEntitys(List<T> entitys)
157         {
158             foreach (var item in entitys)
159             {
160                 db.Set<T>().Attach(item);
161                 db.Entry<T>(item).State = System.Data.Entity.EntityState.Deleted;
162             }
163             return db.SaveChanges() > 0;
164         }
165         /// <summary>
166         /// 批量物理删除数据,也可以用作单个物理删除--此方法适用于id为int类型的表--性能会比先查询后删除快
167         /// </summary>
168         /// <param name="ids">ids格式:1,3,2</param>
169         /// <returns></returns>
170         public bool DeletePhysicsEntitys(string ids)
171         {
172             //delete from Info_Notice where id in(10)
173             string tableName = typeof(T).Name;//获取表名
174             if (ids.Contains(","))
175             {
176                 ids = ids.Substring(1);
177             }            
178             string sql = string.Format("delete from {0} where id in({1})", tableName, ids);
179             return db.Database.ExecuteSqlCommand(sql) > 0;
180         }
181         /// <summary>
182         /// 批量软删除数据,也可以用作单个软删除--此方法适用于id为int类型的表
183         /// </summary>
184         /// <param name="ids">ids格式:1,3,2</param>
185         /// <returns></returns>
186         public bool DeleteSoftEntitys(string ids)
187         {
188             //update dbo.Info_Notice set Deleted=1 where id in(6,7)
189             string tableName = typeof(T).Name;//获取表名           
190             if (ids.Contains(","))
191             {
192                 ids = ids.Substring(1);
193             }
194             string sql = string.Format("update {0} set Deleted=1 where id in({1})", tableName, ids);
195             return db.Database.ExecuteSqlCommand(sql) > 0;
196 
197         }
198 
199         #endregion
200 
201         #region 4.Select
202         //带条件查询
203         public List<T> GetEntitys(Expression<Func<T, bool>> whereLambds)
204         {
205             return db.Set<T>().Where<T>(whereLambds).ToList<T>();
206         }
207         //带排序查询
208         public List<T> GetEntitys<S>(Expression<Func<T, bool>> whereLambds, bool isAsc, Expression<Func<T, S>> orderByLambds)
209         {
210             var temp = db.Set<T>().Where<T>(whereLambds);
211             if (isAsc)
212             {
213                 return temp.OrderBy<T, S>(orderByLambds).ToList<T>();
214             }
215             else
216             {
217                 return temp.OrderByDescending<T, S>(orderByLambds).ToList<T>();
218             }
219         }
220         public List<T> GetEntitys(string sql, string where, string orderKey, params object[] paramss)
221         {
222 
223             sql = sql + " where 1=1 " + where;
224             sql += " order by " + orderKey;
225             var temp = db.Database.SqlQuery<T>(sql, paramss);
226             return temp.ToList<T>(); ;
227 
228         }
229         //带分页查询
230         public List<T> GetPagedEntitys<S>(int pageIndex, int pageSize, out int rows, out int totalPage, Expression<Func<T, bool>> whereLambds, bool isAsc, Expression<Func<T, S>> orderByLambds)
231         {
232             var temp = db.Set<T>().Where<T>(whereLambds);
233             rows = temp.Count();
234             totalPage = rows % pageSize == 0 ? rows / pageSize : rows / pageSize + 1;
235             temp = isAsc ? temp.OrderBy<T, S>(orderByLambds) : temp.OrderByDescending<T, S>(orderByLambds);
236             temp = temp.Skip<T>(pageSize * (pageIndex - 1)).Take<T>(pageSize);
237 
238             return temp.ToList<T>();
239         }
240         //传统sql结合EF分页实现查询
241         public List<T> GetPagedEntitys(int pageIndex, int pageSize, out int rows, out int totalPage, string where, string orderKey, params object[] paramss)
242         {
243             #region 此种方法会在内存中进行分页---已废弃
244             /*
245             string sqls = "";
246             if (string.IsNullOrEmpty(sql))
247             {
248                 sqls = "select * from " + typeof(T).Name;
249             }
250             else
251             {
252                 sqls = sql;
253             }
254             if (!string.IsNullOrEmpty(where))
255             {
256                 sqls = sqls + " where 1=1 " + where;
257             }
258             if (!string.IsNullOrEmpty(orderKey))
259             {
260                 sqls += " order by " + orderKey;
261             }
262             var temp = db.Database.SqlQuery<T>(sqls, paramss);
263             rows = temp.Count();
264             if (rows % pageSize == 0)
265             {
266                 totalPage = rows / pageSize;
267             }
268             else
269             {
270                 totalPage = rows / pageSize + 1;
271             }
272 
273             temp = temp.Skip(pageSize * (pageIndex - 1)).Take(pageSize);
274             return temp.ToList<T>(); 
275             */
276 
277             #endregion
278 
279 
280             string sqls = "";
281             string tableName = typeof(T).Name;//获取表名
282             string sql = string.Format("select *, row_number() over (order by {0} ) as row_number from {1}", string.IsNullOrEmpty(orderKey) ? "Id" : orderKey, tableName);
283             string where1 = !string.IsNullOrEmpty(where) ? " where 1=1 " + where : "";
284             int tag = (pageIndex - 1) * pageSize;
285             sqls = string.Format(@"select top ({0}) * from 
286                          ( 
287                            {1}
288                            {2}
289                           )  as t
290                          where t.row_number > {3}", pageSize, sql, where1, tag);
291             //获取数据
292             var list = db.Database.SqlQuery<T>(sqls, paramss).ToList<T>();
293 
294             //通过自定义的class R 取得总页码数和记录数
295             string sqlCount = string.Format("select count(1) as Rows from {0} {1}", tableName, where1);
296             rows = db.Database.SqlQuery<R>(sqlCount, paramss).ToList()[0].Rows;
297             totalPage = rows % pageSize == 0 ? rows / pageSize : rows / pageSize + 1;
298 
299             return list;
300 
301         }
302         #endregion
303 
304         public class R
305         {
306             public int Rows { get; set; }
307         }
308 
309     }
310 }

然后新建实体对于的DAL,继承BaseDAL<T>

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

namespace DataAccess.DAL
{
    public class Public_AdPositionDAL : BaseDAL<T_Public_AdPosition>
    {
    }
}

 

第三步:BusinessLogic.BLL说明

新建基类:

  1 using DataAccess.DAL;
  2 using System;
  3 using System.Collections.Generic;
  4 using System.Linq;
  5 using System.Linq.Expressions;
  6 using System.Text;
  7 using System.Threading.Tasks;
  8 
  9 namespace BusinessLogic.BLL
 10 {
 11     /// <summary>
 12     /// BLL层抽象基类
 13     /// </summary>
 14     /// <typeparam name="T"></typeparam>
 15     public abstract class BaseBLL<T> where T : class,new()
 16     {
 17 
 18         protected BaseDAL<T> dal = null;
 19         public BaseBLL()
 20         {
 21             SetDAL();
 22         }
 23         /// <summary>
 24         /// 必须重载的抽象方法,用来实例化 idal
 25         /// </summary>
 26         public abstract void SetDAL();
 27 
 28         #region 1.Add
 29 
 30 
 31         /// <summary>
 32         /// 增加一条数据
 33         /// </summary>
 34         /// <param name="entity"></param>
 35         /// <returns></returns>
 36         public bool AddEntity(T entity)
 37         {
 38 
 39             return dal.AddEntity(entity);
 40         }
 41         /// <summary>
 42         /// 同时增加多条数据到一张表(事务处理)
 43         /// </summary>
 44         /// <param name="entitys"></param>
 45         /// <returns></returns>
 46         public bool AddEntity(List<T> entitys)
 47         {
 48             return dal.AddEntity(entitys);
 49         }
 50         #endregion
 51 
 52         #region 2.Modify
 53         /// <summary>
 54         /// 修改一条数据,会修改所有列的值,没有赋值的属性将会被赋予属性类型的默认值**************
 55         /// </summary>
 56         /// <param name="entity"></param>
 57         /// <returns></returns>
 58         public bool ModifyEntity(T entity)
 59         {
 60             return dal.ModifyEntity(entity);
 61         }
 62         public bool ModifyEntity(List<T> entitys)
 63         {
 64             return dal.ModifyEntity(entitys);
 65         }
 66         /// <summary>
 67         /// 修改一条数据,会修改指定列的值
 68         /// </summary>
 69         /// <param name="entity">要修改的实体对象</param>
 70         /// <param name="proNames">要修改的属性名称</param>
 71         /// <returns></returns>
 72         public bool ModifyEntity(T entity, params string[] proNames)
 73         {
 74             return dal.ModifyEntity(entity, proNames);
 75         }
 76         /// <summary>
 77         /// 根据条件批量修改指定的列********************
 78         /// </summary>
 79         /// <param name="entity"></param>
 80         /// <param name="whereLambds"></param>
 81         /// <param name="proNames"></param>
 82         /// <returns></returns>
 83         public bool ModifyEntity(T entity, Expression<Func<T, bool>> whereLambds, params string[] proNames)
 84         {
 85             return dal.ModifyEntity(entity, whereLambds, proNames);
 86         }
 87         #endregion
 88 
 89         #region 3.Delete
 90 
 91         /// <summary>
 92         /// 删除一个实体对象
 93         /// </summary>
 94         /// <param name="entity"></param>
 95         /// <returns></returns>
 96         public bool DeleteEntity(T entity)
 97         {
 98             return dal.DeleteEntity(entity);
 99         }
100         /// <summary>
101         /// 根据条件批量删除实体对象
102         /// </summary>
103         /// <param name="whereLambds"></param>
104         /// <returns></returns>
105         public bool DeleteEntityByWhere(Expression<Func<T, bool>> whereLambds)
106         {
107             return dal.DeleteEntityByWhere(whereLambds);
108         }
109         /// <summary>
110         /// 事务批量删除实体对象
111         /// </summary>
112         /// <param name="entitys"></param>
113         /// <returns></returns>
114         public bool DeleteEntitys(List<T> entitys)
115         {
116             return dal.DeleteEntitys(entitys);
117         }
118         private int Del(string ids)
119         {
120             int tag = 0;
121             if (string.IsNullOrEmpty(ids))
122             {
123                 tag++;
124             }
125             var idlist = ids.Split(new char[] { , }, StringSplitOptions.RemoveEmptyEntries).ToList();
126             List<int> idInt = new List<int>();
127             idlist.ForEach(c =>
128             {
129                 int temp = 0;
130                 if (!int.TryParse(c, out temp))
131                 {
132                     tag++;
133                 }
134 
135             });
136             return tag;
137         }
138         /// <summary>
139         /// 批量软删除数据,也可以用作单个软删除--此方法适用于id为int类型且具有Deleted字段的表
140         /// 如果删除单个数据格式为:整数格式 如 id=1。如果批量删除数据格式为:1,2,44 如 id=1,4,3。
141         /// </summary>
142         /// <param name="ids">ids格式:1,3,2</param>
143         /// <returns></returns>
144         public bool DeleteSoftById(string ids)
145         {            
146             if (Del(ids) > 0)
147             {
148                 return false;
149             }
150             return dal.DeleteSoftEntitys(ids);
151         }
152         /// <summary>
153         /// 批量(单个)物理删除数据---此方法适用于id为int类型的表
154         ///如果删除单个数据格式为:整数格式 如 id=1。如果批量删除数据格式为:1,2,44 如 id=1,4,3。
155         /// </summary>
156         /// <param name="id">如果删除单个数据格式为:整数格式 如 id=1。如果批量删除数据格式为:1,2,44 如 id=1,4,3。</param>
157         /// <returns></returns>
158         public bool DeletePhysicsById(string ids)
159         {
160 
161             if (Del(ids) > 0)
162             {
163                 return false;
164             }
165             return dal.DeletePhysicsEntitys(ids);
166             //return DeleteEntityByWhere(c => idInt.Contains(c.Id));
167         }
168         #endregion
169 
170         #region 4.Select
171         //带条件查询
172         public List<T> GetEntitys(Expression<Func<T, bool>> whereLambds)
173         {
174             return dal.GetEntitys(whereLambds);
175         }
176         //带排序查询
177         public List<T> GetEntitys<S>(Expression<Func<T, bool>> whereLambds, bool isAsc, Expression<Func<T, S>> orderByLambds)
178         {
179             return dal.GetEntitys(whereLambds, isAsc, orderByLambds);
180         }
181         public List<T> GetEntitys(string sql, string where, string orderKey, params object[] paramss)
182         {
183             return dal.GetEntitys(sql, where, orderKey, paramss);
184         }
185         //带分页查询
186         public List<T> GetPagedEntitys<S>(int pageIndex, int pageSize, out int rows, out int totalPage, Expression<Func<T, bool>> whereLambds, bool isAsc, Expression<Func<T, S>> orderByLambds)
187         {
188             return dal.GetPagedEntitys(pageIndex, pageSize, out rows, out totalPage, whereLambds, isAsc, orderByLambds);
189         }
190 
191         /// <summary>
192         /// 传统sql结合EF分页实现查询
193         /// </summary>
194         /// <param name="pageIndex"></param>
195         /// <param name="pageSize"></param>
196         /// <param name="rows"></param>
197         /// <param name="totalPage"></param>
198         /// <param name="sql">sql可为空:select * from 实体名</param>
199         /// <param name="where">条件:and 字段=值</param>
200         /// <param name="orderKey">排序:id desc,name asc</param>
201         /// <param name="paramss">参数化查询时的可变参数</param>
202         /// <returns></returns>
203         public List<T> GetPagedEntitys(int pageIndex, int pageSize, out int rows, out int totalPage, string where, string orderKey, params object[] paramss)
204         {
205 
206             return dal.GetPagedEntitys(pageIndex, pageSize, out rows, out totalPage, where, orderKey, paramss);
207 
208         }
209         #endregion
210     }
211 }

然后新建实体对于的BLL,继承BaseBLL<T>

 1 using DataAccess.DAL;
 2 using Domain.Entity;
 3 using System;
 4 using System.Collections.Generic;
 5 using System.Linq;
 6 using System.Text;
 7 using System.Threading.Tasks;
 8 
 9 namespace BusinessLogic.BLL
10 {
11     public class Public_AdPositionBLL : BaseBLL<T_Public_AdPosition>
12     {
13         private Public_AdPositionDAL Public_AdPositionDAL = null;
14         public override void SetDAL()
15         {            
16             Public_AdPositionDAL = Infrastructure.Ioc.DALFactory.Public_AdPositionDAL;
17             dal = Public_AdPositionDAL;
18         }
19     }
20 }

我们在BusinessLogic.BLL上放个BLLFactory类,让UI层从这个类中取数据。

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Threading.Tasks;
 6 
 7 namespace BusinessLogic.BLL
 8 {
 9     public class BLLFactory
10     {
11         private BLLFactory() { }
12         public static readonly Public_SettingBLL Public_SettingBLL = new Public_SettingBLL();
13         public static readonly Public_AdPositionBLL Public_AdPositionBLL = new Public_AdPositionBLL();
14     }
15 }

 

下一步就是UI层的处理了~~~~~未完待续

EF6.0+APS.NET MVC5.0项目初探四(填充各个程序集),布布扣,bubuko.com

EF6.0+APS.NET MVC5.0项目初探四(填充各个程序集)

标签:des   style   blog   http   color   os   io   数据   

原文地址:http://www.cnblogs.com/eggTwo/p/3887203.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!