EF 增删改查 泛型方法

1.定义泛型类

namespace Crm.Data.Logic.Repository
{
    public abstract class AbstractRepository<TC, T> : IDisposable
        where TC : DbContext, new()
        where T : class
    {
        private TC _entities = new TC();
        private bool _disposed;
        protected TC Context
        {
            get
            {
                return _entities;
            }
            set
            {
                _entities = value;
            }
        }
        public virtual IQueryable<T> All
        {
            get
            {
                return GetAll();
            }
        }
        public virtual IQueryable<T> AllIncluding(params Expression<Func<T, object>>[] includeProperties)
        {
            IQueryable<T> queryable = _entities.Set<T>();
            return includeProperties.Aggregate(queryable, (current, expression) => current.Include(expression));
        }
        public virtual IQueryable<T> GetAll()
        {
            return _entities.Set<T>();
        }
        public virtual T Find(params object[] keyValues)
        {
            return _entities.Set<T>().Find(keyValues);
        }
        public virtual IQueryable<T> FindBy(Expression<Func<T, bool>> predicate)
        {
            return _entities.Set<T>().Where(predicate);
        }
        public virtual void Add(T entity)
        {
            _entities.Set<T>().Add(entity);
        }

public virtual void BulkInsert(List<T> list)
        {
            var tblName = typeof(T).Name;
            BulkInsert(_entities.Database.Connection.ConnectionString, tblName, list);
        }

public static void BulkInsert(string connection, string tableName, IList<T> list)
        {
            using (var bulkCopy = new SqlBulkCopy(connection))
            {
                bulkCopy.BatchSize = list.Count;
                bulkCopy.DestinationTableName = tableName;

var table = new DataTable();
                var props = TypeDescriptor.GetProperties(typeof(T))
                    //Dirty hack to make sure we only have system data types
                    //i.e. filter out the relationships/collections
                                           .Cast<PropertyDescriptor>()
                                           .Where(propertyInfo => propertyInfo.PropertyType.Namespace != null
                                               && propertyInfo.PropertyType.Namespace.Equals("System"))
                                           .ToArray();

foreach (var propertyInfo in props)
                {
                    bulkCopy.ColumnMappings.Add(propertyInfo.Name, propertyInfo.Name);
                    table.Columns.Add(propertyInfo.Name, Nullable.GetUnderlyingType(propertyInfo.PropertyType) ?? propertyInfo.PropertyType);
                }

var values = new object[props.Length];
                foreach (var item in list)
                {
                    for (var i = 0; i < values.Length; i++)
                    {
                        values[i] = props[i].GetValue(item);
                    }

table.Rows.Add(values);
                }

bulkCopy.WriteToServer(table);
            }
        }

public virtual void Delete(T entity)
        {
            _entities.Set<T>().Remove(entity);
        }
        public virtual void Edit(T entity)
        {
            _entities.Entry(entity).State = (EntityState.Modified);
        }
        public virtual void Upsert(T entity, Func<T, bool> insertExpression)
        {
            if (insertExpression(entity))
            {
                Add(entity);
            }
            else
            {
                Edit(entity);
            }
        }
        public virtual void Save()
        {
            _entities.SaveChanges();
        }

public virtual DataTable PageQuery(int page, int pageSize,
            string sort, string where, out int total)
        {
            var viewName = typeof (T).Name;
            var paras = new List<SqlParameter>
                                {
                                    new SqlParameter("tblName", "dbo."+viewName),
                                    new SqlParameter("fldName", "*"),
                                    new SqlParameter("pageSize", pageSize),
                                    new SqlParameter("page", page),
                                    new SqlParameter("fldSort", sort),
                                    new SqlParameter("strCondition", where),
                                    new SqlParameter("pageCount", SqlDbType.Int){Direction = ParameterDirection.Output},
                                };
            var countParameter = new SqlParameter
            {
                ParameterName = "counts",
                SqlDbType = SqlDbType.Int,
                Direction = ParameterDirection.Output
            };
            var strParameter = new SqlParameter("strSql", SqlDbType.NVarChar, 4000) { Direction = ParameterDirection.Output };

paras.Add(countParameter);
            paras.Add(strParameter);

var conn = _entities.Database.Connection.ConnectionString;
            var ds = SqlHelper.ExecuteDataset(conn, CommandType.StoredProcedure,
                                              "dbo.PagedQuery", paras.ToArray());
            total = countParameter.Value == DBNull.Value ? 0 : Convert.ToInt32(countParameter.Value);
            return ds.Tables[0];
        }

public virtual List<T> PageQueryList(int page, int pageSize,
            string sort, string where, out int total)
        {
            var viewName = typeof(T).Name;
            var paras = new List<SqlParameter>
                                {
                                    new SqlParameter("tblName", "dbo."+viewName),
                                    new SqlParameter("fldName", "*"),
                                    new SqlParameter("pageSize", pageSize),
                                    new SqlParameter("page", page),
                                    new SqlParameter("fldSort", sort),
                                    new SqlParameter("strCondition", where),
                                    new SqlParameter("pageCount", SqlDbType.Int){Direction = ParameterDirection.Output},
                                };
            var countParameter = new SqlParameter
            {
                ParameterName = "counts",
                SqlDbType = SqlDbType.Int,
                Direction = ParameterDirection.Output
            };
            var strParameter = new SqlParameter("strSql", SqlDbType.NVarChar, 4000) { Direction = ParameterDirection.Output };

paras.Add(countParameter);
            paras.Add(strParameter);

//var conn = _entities.Database.Connection.ConnectionString;
            //var ds = SqlHelper.ExecuteDataset(conn, CommandType.StoredProcedure,
            //                                  "dbo.PagedQuery", paras.ToArray());
            //total = countParameter.Value == DBNull.Value ? 0 : Convert.ToInt32(countParameter.Value);
            var ret =_entities.Database.SqlQuery<T>(
                "dbo.PagedQuery @tblName,@fldName,@pageSize,@page,@fldSort,@strCondition,@pageCount out,@counts out,@strSql out",
                paras.ToArray()).ToList();
            total = countParameter.Value == DBNull.Value ? 0 : Convert.ToInt32(countParameter.Value);
            return ret;
        }

protected virtual void Dispose(bool disposing)
        {
            if (!_disposed && disposing)
            {
                _entities.Dispose();
            }
            _disposed = true;
        }
        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }
    }
}

2. 具体类继承泛型类

namespace Crm.Data.Logic.Logic
{
    public class CrmDispatchLogic:AbstractRepository<LifeEntities,Crm_Dispatch>
    {
        
    }
}

3. 使用具体类

var dispatchSvc = new CrmDispatchLogic();
        var dispatchModel = dispatchSvc.GetAll().FirstOrDefault(m => m.Handler == opId
            && m.IsUse == 1);
        if (dispatchModel != null)
        {}

时间: 2024-10-07 22:16:18

EF 增删改查 泛型方法的相关文章

WPF MVVM+EF增删改查 简单示例(二) 1对1 映射

WPF MVVM+EF增删改查 简单示例(一)实现了对学生信息的管理. 现在需求发生变更,在录入学生资料的时候同时需要录入学生的图片信息,并且一名学生只能有一张图片资料.并可对学生的图片资料进行更新. 添加了那些功能,先看看效果图: 第一步:添加实体类StudentPhotoEntity.cs public class StudentPhotoEntity { public int StudentId { get; set; } public byte[] StudentPhoto { get;

EF增删改查+使用Expression进行排序分页

注:以下部分来自<ASP.NET MVC 企业级实战>一书的摘抄和改写以及部分个人学习心得. EF简单增删改查 增加 public static int Add() { using (NorthwindEntities db=new NorthwindEntities()) { Customers cs2 = new Customers { CustomerID = "11", ContactName="aa4444sa", Address="

MVC3.0 EF增删改查的封装类

本人亲身使用EF CodeFirst,因为增删改查都是使用EF内置的一些方法,我想把它封装到一个类调用就行了.结合网上的资料和自己的整理,若有不对的地方望斧正,感激不尽.直接上代码吧.我就用新闻的增删改查做例子. 这是项目的整个结构图: Views文件夹的文件 1.先看Index.cshtml页面的代码把 Index.cshtml(列表页面) @model IEnumerable<NewsMvc.Models.News> @{ Layout = null; } <!DOCTYPE htm

构建ASP.NET MVC4+EF5+EasyUI+Unity2.x注入的后台管理系统(5)-EF增删改查by糟糕的代码

上一讲我们创建了一系列的解决方案,我们通过一个例子来看看层与层之间的关系. 我们把Controllers分离出来了BLL层和DAL层 BLL专注于业务上的处理 DAL专注于数据访问层的处理 而Controller跟清楚的与View交互 我们上一讲已经在EF添加了一个实体SysSample 下面我们创建IDAL,DAL,IBLL,BLL的代码吧 using App.Models; using System.Linq; namespace App.IDAL { public interface IS

webapi+EF(增删改查)

第一步,Model建立Ado.net实体模型. 第二部,Controller建立增删查改方法 public static HttpResponseMessage toJson(Object obj)        {            String str;            if (obj is String || obj is Char)            {                str = obj.ToString();            }           

EF增删改查

//查询 //查询指定字符串出现的个数,类似于模糊查询select count(*) from Book where Name like '%字符串%' db.Book.Where(x => x.Name.Contains(txtName.Text.Trim())).Count(); //接收查询的数据 List<Book> bk = db.Book.ToList(); dataGridView1.DataSource = bk; //添加 Book bk = new Book(){ A

EF CodeFirst增删改查之‘CRUD’

最近悟出来一个道理,在这儿分享给大家:学历代表你的过去,能力代表你的现在,学习代表你的将来. 十年河东十年河西,莫欺少年穷 学无止境,精益求精    本篇旨在学习EF增删改查四大操作 上一节讲述了EF CodeFirst 创建数据库,本节继续引用上一节的相关类学习EF的CRUD操作 废话少说,直接上要点,上一节中的模型类我作了如下修改: using System; using System.Collections.Generic; using System.ComponentModel.Data

EF中的增删改查

在上一篇中简单的介绍了一下有关EF的一些概念,都是小编的一些个人理解,懂的不多,想深入学习的可以从网上查看一些其他资料. 下面紧接着上一篇所说,来从代码上看一下EF容器是如何实现与后台数据库之间的增删改查的. 1.EF包装类 什么是EF包装类呢?举个例子,我们平时用SQL语句写增删改查时,用的都是一些Insert.Update.Delete等语句来实现增删改查,所以我们把放到EF容器的东东也要做一个标签,来指明这个东东是要添加.更新.还是要删除呢. 正如上图所示就是这么简单的操作,就完成了对数据

[EF]使用EF简单增删改查

目录 认识EF 添加数据 删除数据 修改数据 查询数据 总结 认识EF ADO.NET Entity Framework 是微软以ADO.NET为基础所发展出来的对象关系对伊(O/R Mapping)解决方案,早起被称为ObjectSpage,最新版本EF6. 实体框架Entity Framework是ADO.NET中的一组支持面向数据的软件应用程序的技术.是微软的一个ORM框架. 什么是O/R Mapping 广义上,ORM指的是面向对象模型和关系数据库的数据结构之间的相互转换. 狭义上,OR