MVC,EF 小小封装

1.项目中经常要用到 EF,有时候大多数的增删改查都是重复性的东西,本次封装就是为了快速开发,期间没有考虑到架构上的各种思想,就感觉到欠缺点什么东西所以这次将这些拉出来,有存在问题的话还请各位多多指导。

2.封装后从压力和并发上也没有去测试,有兴趣的小伙伴还望给看下。好了不废话了直接上了。
 a.先看下大概结构如下   按照顺序介绍  a.1: 实体就是一般大家手动写的实体  

a.2:  DALContext.cs 代码如下:

namespace Test.Web.Site.DAL
{
     public class DALContext<T> : DbContext
          where T : class
     {
          public DALContext(string con)
               : base(con){}

          public DALContext(){}

          public DbSet<T> TV { get; set; }
     }
}

a.3  BaseDAL.cs  主要的增删改方法

namespace Test.Web.Site.DAL
{

     public class BaseDAL<TEntity>
          where TEntity : class,new()
     {
          private static readonly object s_lock = new object();
          private static string constr = "xxxConn";//默认一个字符串
          public BaseDAL(string con = "")
          {
               if (con != constr && con.Length > 0)
               {
                    lock (s_lock)
                    {
                         constr = con;
                    }
               }
          }
#region Modify and Delete public virtual bool Insert(TEntity entity) { using (var db = new DALContext<TEntity>(constr)) { db.Set<TEntity>().Add(entity); return db.SaveChanges() > 0; } } public virtual bool Delete(object col) { using (var db = new DALContext<TEntity>(constr)) { TEntity entityToDelete = db.Set<TEntity>().Find(col); if (entityToDelete != null) { return Delete(entityToDelete); } else { return false; } } } public virtual bool Delete(Expression<Func<TEntity, bool>> predicate) { TEntity entityToDelete = Get(predicate); if (entityToDelete != null) { return Delete(entityToDelete); } else { return false; } } public virtual IEnumerable<TEntity> InsertAll(List<TEntity> list) { using (var db = new DALContext<TEntity>(constr)) { var dbSet = db.Set<TEntity>(); List<TEntity> tList = new List<TEntity>(); foreach (var item in list) { try { db.Set<TEntity>().Add(item); } catch (Exception) { tList.Add(item); throw; } } db.SaveChanges(); return tList; } } public virtual IEnumerable<TEntity> UpdateAll(List<TEntity> list) { using (var db = new DALContext<TEntity>(constr)) { var dbSet = db.Set<TEntity>(); List<TEntity> tList = new List<TEntity>(); foreach (var item in list) { try { var entity = dbSet.Attach(item); db.Entry(item).State = System.Data.EntityState.Modified; } catch (Exception) { tList.Add(item); throw; } } db.SaveChanges(); return tList; } } public virtual bool Update(TEntity entityToUpdate) { using (var db = new DALContext<TEntity>(constr)) { var dbSet = db.Set<TEntity>(); var entity = dbSet.Attach(entityToUpdate); db.Entry(entityToUpdate).State = System.Data.EntityState.Modified; return db.SaveChanges() > 0; } } #endregion } }

a.4 DatabaseExtensions.cs 一个EF 扩展类 用于 连接其他数据库比如 mysql(参考的网络资源),执行sql语句查询视图有需要可在下方评论,我会及时回复

a.5 :  Test.Web.Site.BLL  对Control 开放的一系列方法 ,这里仅列举了部分代码出来,如有需要可在下方评论我及时回复你。

namespace Test.Web.Site.BLL
{
    public class DataBLL<T>
         where T : class,new()
    {
        // 连接字符串
        public DataBLL(string constr = "")
        {
            SingletonBase<BaseDAL<T>>.Initialize(new BaseDAL<T>(constr));
        }public T Get(Expression<Func<T, bool>> filter, string includeProperties = "")
        {
            return SingletonBase<BaseDAL<T>>.Instance.Get(filter, includeProperties);
        }

        // 插入一个实体
        public bool AddEntity(T t_entity)
        {
            return SingletonBase<BaseDAL<T>>.Instance.Insert(t_entity);
        }
        // 跟新实体
        public bool Update(T t_enttiy)
        {
            return SingletonBase<BaseDAL<T>>.Instance.Update(t_enttiy);
        }
        // 依据sql查询 list 
        public IEnumerable<object> GetListBySql(string query,bool otherdb = true)
        {
            return SingletonBase<BaseDAL<T>>.Instance.GetBySql(query, otherdb);
        }
        // 删除满足条件的所有数据
        public IEnumerable<T> DeleteAll(Expression<Func<T, bool>> predicate)
        {
            return SingletonBase<BaseDAL<T>>.Instance.DeleteAll(predicate);
        }
        // 批量更新 list 
        public IEnumerable<T> UpdateAll(List<T> list)
        {
             return SingletonBase<BaseDAL<T>>.Instance.UpdateAll(list);
        }
        // 批量添加
        public IEnumerable<T> InsertAll(List<T> list)
        {
             return SingletonBase<BaseDAL<T>>.Instance.InsertAll(list);
        }
    }
}

3.Control 调用只需要类似:

Account currAccount = new DataBLL<Account>(ConfigHelper.Constr_read).Get(p => p.UserId == 1111);

  new DataBLL<Account>.GetPage(out totalCount, query.Expression, pageIndex, pageSize, k => k.OrderByDescending(_ => _.CreateTime)).ToList();

 

总结:到此就结束了所有代码可复制过去加入EF引用就开始用了。有发现问题的小伙伴敬请抛砖。小弟不胜感激。

 

posted on 2015-12-28 20:31  无觉-李敏  阅读(2336)  评论(10编辑  收藏  举报