Entity Framework底层操作封装V2版本号(2)
这个类是真正的数据库操作类。上面的那个类仅仅是调用了这个封装类的方法进行的操作
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Linq.Expressions;
using System.Data.Entity;
using System.Data.Linq;
using System.Data.Objects;
using System.Reflection;
using System.Threading;
using System.Data;
using System.Data.Objects.DataClasses;
using JFrame.Utility; namespace JFrame.AccessCommon
{
public class DataCommon
{
static readonly string Connection = "name=EntitiesContainer";
static readonly string ContainerName = "EntitiesContainer";
ObjectContext entities;
public DataCommon(string Connection, string ContainerName = "EntitiesContainer")
{
entities = new ObjectContext(Connection);
entities.DefaultContainerName = ContainerName;
} //POMonitorDBEntities entities = new ENTITY.POMonitorDBEntities(Connection); #region 依据SQL语句查询数据
public IEnumerable<T> ExecuteQuery<T>(string conn, string query, params object[] parms)
{
try
{
if (string.IsNullOrEmpty(conn))
{
return entities.ExecuteStoreQuery<T>(query, parms);
}
else
{
DataContext myDC = new DataContext(conn);
return myDC.ExecuteQuery<T>(query, parms);
}
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
public IEnumerable<T> ExecuteQuery<T>(string query)
{
return ExecuteQuery<T>(string.Empty, query, new object[] { });
}
#endregion #region 运行操作类型SQl语句
/// <summary>
/// 运行SQL命令
/// </summary>
/// <param name="sqlCommand"></param>
/// <returns></returns>
public int ExecuteSqlCommand(string sqlCommand, string connection = null)
{
if (string.IsNullOrEmpty(connection))
return entities.ExecuteStoreCommand(sqlCommand); //ExecuteCommand(sqlCommand);
else
{
ObjectContext entitiesNew = new ObjectContext(connection);
return entitiesNew.ExecuteStoreCommand(sqlCommand);
}
}
/// <summary>
/// 运行SQL命令
/// </summary>
/// <param name="sqlCommand"></param>
/// <returns></returns>
public void ExecuteSqlCommand(string sqlCommand)
{
ExecuteSqlCommand(connection: string.Empty, sqlCommand: sqlCommand);
}
#endregion #region 私有方法
private ObjectSet<T> GetTable<T>() where T : class
{
try
{
ObjectSet<T> customers = entities.CreateObjectSet<T>();
return customers;
}
catch (Exception ex)
{
throw ex;
} }
#endregion #region 统计指定条件的数据量
/// <summary>
/// 统计指定条件的数据量
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="query"></param>
/// <returns></returns>
public virtual int Count<T>(Expression<Func<T, bool>> query) where T : class
{
var table = GetTable<T>();
return (from t in table
select t).Where(query).Count();
}
#endregion #region 获取单个实体
/// <summary>
/// 获取单个实体
/// </summary>
/// <typeparam name="T">泛型类型參数</typeparam>
/// <param name="express">查询条件</param>
/// <returns></returns>
public virtual T GetSingleEntity<T>(Expression<Func<T, bool>> query) where T : class
{
try
{
var table = GetTable<T>();
return (from t in table
select t).Where(query).SingleOrDefault();
}
catch (Exception ex)
{
throw ex;
}
} #endregion ///<summary>
///获取主键,此方式仅仅适用于edmx数据表结构
///</summary>
///<param name="infos"></param>
///<returns></returns>
private string getPrimaryKey(PropertyInfo[] infos)
{
string columnName = string.Empty;
foreach (PropertyInfo propertyInfo in infos)
{
object[] customInfos = propertyInfo.GetCustomAttributes(typeof(EdmScalarPropertyAttribute), true);
if (customInfos == null
|| customInfos.Length == 0)
return string.Empty; EdmScalarPropertyAttribute limit = customInfos.GetValue(0) as EdmScalarPropertyAttribute;
if (limit.EntityKeyProperty)
{
return columnName = propertyInfo.Name;
}
}
return columnName; } //protected override string GetEntitySetName()
//{
// return context.Products.EntitySet.Name; //} #region 更新实体
public bool Update<T>(T entity, string PrimaryKey, object PrimaryKeyValue) where T : EntityObject
{
Type type = typeof(T);
string strName = entities.Connection.ConnectionString.Replace("name=", "");
EntityKey key = null;
try
{
entity.EntityKey = entities.CreateEntityKey(type.Name, entity);
}
catch (Exception ex)
{ } try
{
key = entity.EntityKey;//new EntityKey("Entities." + type.Name, PrimaryKey, PrimaryKeyValue);
}
catch (Exception ex)
{ }
object propertyValue = null;
T entityFromDB = (T)entities.GetObjectByKey(key); if (null == entityFromDB)
return false;
PropertyInfo[] properties1 = entityFromDB.GetType().GetProperties();
foreach (PropertyInfo property in properties1)
{
propertyValue = null;
if (null != property.GetSetMethod())
{
PropertyInfo entityProperty =
entity.GetType().GetProperty(property.Name);
if (entityProperty.PropertyType.BaseType ==
Type.GetType("System.ValueType") ||
entityProperty.PropertyType ==
Type.GetType("System.String")) propertyValue = entity.GetType().GetProperty(property.Name).GetValue(entity, null);
if (propertyValue == null)
{
Thread.Sleep(50);
propertyValue = entity.GetType().GetProperty(property.Name).GetValue(entity, null);
}
if (null != propertyValue)
{
try
{
string Name = property.Name;// "Reference";
if (Name.IndexOf("Reference") < 0)
{
property.SetValue(entityFromDB, propertyValue, null);
}
}
catch (Exception ex) { }
}
}
} entities.SaveChanges();
return true; } #endregion #region 获取相关的实体信息
/// <summary>
/// 分页_获取指定页的数据集合
/// </summary>
/// <typeparam name="T">泛型类型參数</typeparam>
/// <param name="query">查询条件</param>
/// <param name="pageSize">每页显示数量</param>
/// <param name="pageNum">当前页号</param>
/// <param name="pageTotal">总页数</param>
/// <param name="datasTotal">总数据量</param>
/// <returns></returns>
public virtual List<T> GetAllEntity<T>(Expression<Func<T, bool>> query, PagingInfo PageInfo, Func<T, object> orderByDesc) where T : class
{
var table = GetTable<T>(); PageInfo.TotalRecord = (from t in table
select t).Where(query.Compile()).Count();
PageInfo.TotalPage = PageInfo.TotalRecord / PageInfo.PageSize + 1;
//string Sql=(table.Where(query.Compile()) as ObjectQuery).ToTraceString();
return (from t in table
select t).Where(query.Compile()).OrderByDescending(orderByDesc).Skip(PageInfo.PageSize * (PageInfo.PageIndex - 1)).Take(PageInfo.PageSize).ToList();
}
/// <summary>
/// 分页_获取指定页的数据集合
/// </summary>
/// <typeparam name="T">泛型类型參数</typeparam>
/// <param name="query">查询条件</param>
/// <param name="pageSize">每页显示数量</param>
/// <param name="pageNum">当前页号</param>
/// <param name="pageTotal">总页数</param>
/// <param name="datasTotal">总数据量</param>
/// <returns></returns>
public virtual List<T> GetAllEntity<T>(Expression<Func<T, bool>> query, Func<T, object> orderByDesc, int pageSize, int pageNum, out int pageTotal, out int datasTotal) where T : class
{
var table = GetTable<T>(); datasTotal = (from t in table
select t).Where(query).Count(); pageTotal = (int)Math.Ceiling((double)datasTotal / pageSize);
return (from t in table
select t).Where(query).OrderByDescending(orderByDesc).Skip(pageSize * (pageNum - 1)).Take(pageSize).ToList();
}
/// <summary>
/// 获取指定条件的实体集合 /// </summary>
/// <typeparam name="T">泛型类型參数</typeparam>
/// <param name="query">查询条件</param>
/// <returns></returns>
public virtual List<T> GetAllEntity<T>(Expression<Func<T, bool>> query) where T : class
{
var table = GetTable<T>();
return (from t in table
select t).Where(query).ToList();
} /// <summary>
/// 获取指定条件的实体集合 /// </summary>
/// <typeparam name="T">泛型类型參数</typeparam>
/// <param name="query">查询条件</param>
/// <param name="orderAsc"></param>
/// <returns></returns>
public virtual List<T> GetAllEntity<T>(Expression<Func<T, bool>> query, bool isAsc, Func<T, object> order) where T : class
{
var table = GetTable<T>();
if (isAsc)
return (from t in table
select t).Where(query).OrderBy(order).ToList();
return (from t in table
select t).Where(query).OrderByDescending(order).ToList();
} public virtual List<T> GetAllEntity<T>() where T : class
{
var table = GetTable<T>();
return (from t in table
select t).ToList();
}
#endregion #region 新增实体
/// <summary>
/// 新增单个实体
/// </summary>
/// <typeparam name="T">泛型类型參数</typeparam>
/// <param name="entity">待插入的实体</param>
/// <returns></returns>
public virtual void InsertEntity<T>(T entity) where T : class
{
var table = GetTable<T>();
table.AddObject(entity);
entities.SaveChanges();
}
/// <summary>
/// 批量新增实体
/// </summary>
/// <typeparam name="T">泛型类型參数</typeparam>
/// <param name="entityList">待加入的实体集合</param>
/// <returns></returns>
public virtual void BatchInsertEntity<T>(List<T> entityList) where T : class
{
if (entityList.Count > 0)
{
var table = GetTable<T>();
foreach (var item in entityList)
{
table.AddObject(item);//DeleteAllOnSubmit(toDeletedColl);
}
entities.SaveChanges();
}
}
#endregion #region 删除实体
/// <summary>
/// 依据条件删除指定实体
/// </summary>
/// <typeparam name="T">实体</typeparam>
/// <param name="query">条件</param>
/// <returns>bool</returns>
public virtual void DeleteEntitys<T>(Expression<Func<T, bool>> query) where T : class
{
var table = GetTable<T>();
var toDeletedColl = table.Where(query);
if (toDeletedColl != null && toDeletedColl.Count() > 0)
{
foreach (var item in toDeletedColl)
{
table.DeleteObject(item);//DeleteAllOnSubmit(toDeletedColl);
}
entities.SaveChanges();
}
}
#endregion
}
}
Entity Framework底层操作封装V2版本号(2)的更多相关文章
- Entity Framework底层操作封装V2版本号(4)
这个版本号里面.由于涉及到了多库的操作.原有的系统方法不能做到这种事情了.所以这里有了一点差别 这个类的主要用作就是,连接字符串的作用,默认是指向默认配置里面的,可是你能够指向其它的连接 using ...
- Entity Framework底层操作封装V2版本号(1)
由于同志们一直给我提建议说.曾经发的版本号有问题.所以经过了我这一年多的使用和扩展,如今方法基本稳定了. 如今贴出来给大家使用: 首先上场的是数据库操作层: using System; using S ...
- Entity Framework底层操作封装V2版本号(3)
如今是附加的,组合查询须要的扩展类.大家知道lanmda表达式的组合条件比較麻烦,所以就加了一样一个类,方便进行组合查询: using System; using System.Collections ...
- Entity Framework底层操作封装V2版本号(5)
这个框架到如今最大的变化立即就要出现了,哪就是对缓存的使用.由于系统常常要去读取数据库数据.可是大家知道.数据库的处理能力是有限的,所以对于一些数据量不大,可是又 须要常常去读取的功能来说.更好的方法 ...
- entity framework 时间操作
).FirstOrDefault(); if (useractiveentity == null) { UserActive userActive = new UserActive(); userAc ...
- .NET Entity Framework入门操作
Entity Framework是微软借鉴ORM思想开发自己的一个ORM框架. ORM就是将数据库表与实体对象(相当于三层中的Model类)相互映射的一种思想. 最大的优点就是非常方便的跨数据库平台. ...
- UWP: 在 UWP 中使用 Entity Framework Core 操作 SQLite 数据库
在应用中使用 SQLite 数据库来存储数据是相当常见的.在 UWP 平台中要使用 SQLite,一般会使用 SQLite for Universal Windows Platform 和 SQLit ...
- Entity Framework 基础操作(1)
EF是微软推出的官方ORM框架,默认防注入可以配合LINQ一起使用,更方便开发人员. 首先通过SQLSERVER现在有的数据库类生产EF 右键->添加->新建项,选择AOD.NET实体数据 ...
- 实体框架Entity Framework 4.1快速入门
介 绍 在旧的Entity 框架中,开发者可以从已存在的数据库中产生业务实体的模型,这种开发方法被称为数据库驱动的开发方法.而在4.1的Entity Framework中,支开发者先创建实体业务类,然 ...
随机推荐
- Jenkins自动部署到(远程)tomcat服务器
Jenkins的流程: 1.从版本控制中获取代码 ->2. 使用maven编译生成相应的包(jar,war) ->3. 部署到指定的地点. 其中2.主要是解决依赖的问题,或许你需要先mvn ...
- ActiveX 控件漏洞挖掘之方法
ActiveX是微软公司提出,并在1996年被正式命名的组件技术.该技术提供了一种通用的开放程序接口,使用这种技术开发的ActiveX控件可以直接集成到IE浏览器或第三方应用程序中,但由于第三方编程等 ...
- ubuntu下修改文件夹权限
常用方法如下: sudo chmod 600 ××× (只有所有者有读和写的权限)sudo chmod 644 ××× (所有者有读和写的权限,组用户只有读的权限)sudo chmod 700 ××× ...
- invalidate和requestLayout方法源码分析
invalidate方法源码分析 在之前分析View的绘制流程中,最后都有调用一个叫invalidate的方法,这个方法是啥玩意?我们来看一下View类中invalidate系列方法的源码(ViewG ...
- 几款很厉害的jQuery数字化签名插件(转)
在浏览器中,我们有很多方式来绘制生成签名效果,并且有很多很棒很智能的jQuery插件.数字化签名是未来的发展方向,正是这个原因我们这里收集并且推荐了四款超棒的jQuery数字化签名插件,希望大家喜欢! ...
- Linux 查看当前时间和修改系统时间
一.查看和修改Linux的时区 1. 查看当前时区 命令: date -R 2. 修改设置Linux服务器时区 方法 A 命令 : tzselect 方法 B 仅限于RedHat Linux 和 Ce ...
- java垃圾回收机制--可达性算法
先说一些题外话,Java虚拟机在执行Java程序的过程中会把它所管理的内存划分为若干个不同的数据区,这些区分为线程私有区和线程共享区 1.线程私有区 a.程序计数器 记录正在执行的虚拟机字节码指令地址 ...
- [Python爬虫] 之四:Selenium 抓取微博数据
抓取代码: # coding=utf-8import osimport refrom selenium import webdriverimport selenium.webdriver.suppor ...
- ES6 中的 Set
收录待用,修改转载已取得腾讯云授权 作者:kurtshen ES6 新增了几种集合类型,本文主要介绍Set以及其使用. 其基本描述为 Set对象是值的集合,你可以按照插入的顺序迭代它的元素. Set中 ...
- centos安装问题集合
1.版本选择可能直接打开www.centos.org打不开,但是可以打开http://wiki.centos.org/zh/Download,直接找到centos下载列表, (1)i386:支持32位 ...