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中,支开发者先创建实体业务类,然 ...
随机推荐
- 【转 :Hibernate 缓存机制】
转自:http://www.cnblogs.com/wean/archive/2012/05/16/2502724.html Hibernate 缓存机制 一.why(为什么要用Hibernate缓存 ...
- 关于LightMapping和NavMesh烘焙的动态载入
熟悉unity的朋友都应该知道,unity有内部LightMapping烘焙和NavMesh寻路的功能.但这些非常好用的功能,都是基于对某个已经保存的关卡(scene)进行烘焙(Bake)的操作,我一 ...
- mysql下float类型使用一些误差详解
单精度浮点数用4字节(32bit)表示浮点数采用IEEE754标准的计算机浮点数,在内部是用二进制表示的如:7.22用32位二进制是表示不下的.所以就不精确了. mysql中float数据类型的问题总 ...
- POJ 3069 Saruman's Army
Saruman's Army Time Limit: 1000MS Memory Limit: 65536K Total Submissions: 6688 Accepted: 3424 De ...
- FatSecret Platform API
在现阶段饮食类的APP发展的非常迅猛,尤其在校园中,学生只需要凭借一个手机就能买到自己想要的食物,真正做到了足不出户.可是如果我们想独立完成一个app就需要有相应的数据支持,这里给大家介绍一个国外的开 ...
- XMPP键盘订制实现图文混排
在现阶段的通信服务中,各种标准都有,因此会出现无法实现相互连通,而XMPP(Extensible Message and presence Protocol)协议的出现,实现了整个及时通信服务协议的互 ...
- 【云计算】使用privilege权限对Docker内核参数进行定制
探讨Docker容器中修改系统变量的方法 探讨完Docker对共享内存状态持久化的支持状况后,我将遗留产品build到一个pre-production image中,测试启动是否OK.很显然,我过于乐 ...
- 理解JAVASCRIPT 中hasOwnProperty()和isPrototypeOf的作用
hasOwnProperty:是用来判断一个对象是否有你给出名称的属性或对象.不过需要注意的是,此方法无法检查该对象的原型链中是否具有该属性,该属性必须是对象本身的一个成员.格式如下: 1. 示例一: ...
- git fatal: https://github.com/TeaCodie/TeaCodie-Website.git/info/refs not found: did you run git update-server-info on the server 错误
错误: fatal: https://github.com/TeaCodie/TeaCodie-Website.git/info/refs not found: did you run git upd ...
- POI生成EXCEL文件(字体、样式、单元格合并、计算公式)
创建一个封装类: package com.jason.excel; import java.io.FileNotFoundException; import java.io.FileOutputStr ...