需要的dll(

EntityFramework.6.0.0
Oracle.ManagedDataAccess.12.1.2400
System.Configuration.dll
EmitMapper.1.0.0

)

代码下载

调用

//连接数据库
static private void DataBaseConnect()
{
string connection = string.Format("User Id={0};Password={1};Data Source=(DESCRIPTION=(ADDRESS=(PROTOCOL=tcp)(HOST={2})(PORT={3}))(CONNECT_DATA=(SERVICE_NAME={4})))",
"zhzepp",
"citms",
"192.168.10.113",
"",
"ORCL");
RepositoryManager.AddConnection("Program", connection);
}

例如查询

 static void Main(string[] args)
{
DataBaseConnect();
using (IRepository<PUNISH_ILLEGALVEHICLE_REALModel> repository = RepositoryManager.CreateRepository<PUNISH_ILLEGALVEHICLE_REALModel>())
{
var list = repository.GetModels().ToList();
}
}

测试实体

using DataBaseTest.DataBase;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks; namespace DataBaseTest
{
[Table("PUNISH_ILLEGALVEHICLE_REAL")]
public class PUNISH_ILLEGALVEHICLE_REALModel : BaseEntity
{
/// <summary>
/// 选项ID
/// </summary>
[Column("PROCESSID"), MaxLength(), Key]
public string processid { get; set; } [Column("SPOTTINGNAME")]
public string Spottingname { get; set; } [Column("PLATENO")]
public string plateno { get; set; } }
}

数据库帮助类

BaseEntity

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks; namespace DataBaseTest.DataBase
{
public abstract class BaseEntity
{
/// <summary>
/// 新增调用
/// </summary>
public virtual void Create()
{
}
/// <summary>
/// 新增调用
/// </summary>
public virtual void CreateApp()
{
}
/// <summary>
/// 编辑调用
/// </summary>
/// <param name="keyValue">主键值</param>
public virtual void Modify(string keyValue)
{
}
/// <summary>
/// 删除调用
/// </summary>
/// <param name="keyValue">主键值</param>
public virtual void Remove(string keyValue)
{
}
/// <summary>
/// 编辑调用
/// </summary>
/// <param name="keyValue">主键值</param>
public virtual void Modify(int keyValue)
{
}
/// <summary>
/// 删除调用
/// </summary>
/// <param name="keyValue">主键值</param>
public virtual void Remove(int keyValue)
{
}
}
}

EFRepository

using Oracle.ManagedDataAccess.Client;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.Common;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Data.SqlClient;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks; namespace DataBaseTest.DataBase
{
[DbConfigurationType(typeof(OracleConfiguration))]
public class EFRepository<TEntity> : IRepository<TEntity> where TEntity : BaseEntity
{
#region 属性
/// <summary>
/// 数据库上下文
/// </summary>
private ProgramContext<TEntity> Context { get; set; }
#endregion #region 构造函数
/// <summary>
/// 构造函数
/// </summary>
public EFRepository()
{
Context = new ProgramContext<TEntity>();
} public EFRepository(string connectionString)
{
Context = new ProgramContext<TEntity>(connectionString);
}
#endregion #region 公共方法
/// <summary>
/// 删除对象
/// </summary>
/// <param name="item"></param>
public bool Delete(string keyValue)
{
if (string.IsNullOrEmpty(keyValue))
return false;
var entity = Find(keyValue);
if (entity == null)
return false;
Context.Models.Remove(Find(keyValue));
return false;
} /// <summary>
/// 按ID获取对象
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
public TEntity Find(object id)
{
return Context.Models.Find(id);
}
/// <summary>
/// 获取所有对象
/// </summary>
/// <returns></returns>
public IQueryable<TEntity> GetModels()
{
return Context.Models;
}
/// <summary>
/// 根据条件进行查询
/// </summary>
/// <typeparam name="Tkey"></typeparam>
/// <param name="whereLambda"></param>
/// <param name="orderbyLambda"></param>
/// <param name="isAsc"></param>
/// <returns></returns>
public IQueryable<TEntity> FindList<Tkey>(Expression<Func<TEntity, bool>> whereLambda, Func<TEntity, Tkey> orderbyLambda, bool isAsc)
{
if (isAsc)
{
var temp = Context.Set<TEntity>().Where(whereLambda)
.OrderBy<TEntity, Tkey>(orderbyLambda);
return temp.AsQueryable();
}
else
{
var temp = Context.Set<TEntity>().Where(whereLambda)
.OrderByDescending<TEntity, Tkey>(orderbyLambda);
return temp.AsQueryable();
}
} /// <summary>
/// 分页查询 + 排序
/// </summary>
/// <typeparam name="Tkey"></typeparam>
/// <param name="pagination"></param>
/// <param name="orderbyLambda"></param>
/// <returns></returns>
public IQueryable<TEntity> FindList<Tkey>(Pagination pagination, Func<TEntity, Tkey> orderbyLambda,out int records,out int total)
{
records = pagination.records;//总记录数
total = pagination.total;//总页数
var data = FindList<Tkey>(pagination.pageIndex, pagination.pageSize, out records, out total, orderbyLambda, pagination.isAsc);
return data;
}
/// <summary>
/// 分页查询 + 条件查询 + 排序
/// </summary>
/// <typeparam name="Tkey"></typeparam>
/// <param name="pagination"></param>
/// <param name="orderbyLambda"></param>
/// <returns></returns>
public IQueryable<TEntity> FindList<Tkey>(Pagination pagination, Expression<Func<TEntity, bool>> whereLambda, Func<TEntity, Tkey> orderbyLambda,out int records, out int total)
{
records = pagination.records;//总记录数
total = pagination.total;//总页数
var data = FindList<Tkey>(pagination.pageIndex, pagination.pageSize, out records, out total, whereLambda, orderbyLambda, pagination.isAsc);
return data;
} /// <summary>
/// 更新对象
/// </summary>
/// <param name="item"></param>
public bool Update(string keyValue, TEntity item)
{
if (item == null || string.IsNullOrEmpty(keyValue))
return false;
var entityToUpdate = Context.Models.Find(keyValue);
if (entityToUpdate == null)
return false;
EmitMapper.ObjectMapperManager.DefaultInstance.GetMapper<TEntity, TEntity>()
.Map(item, entityToUpdate);
return true;
} /// <summary>
/// 执行sql
/// </summary>
/// <param name="sql"></param>
/// <param name="parameters"></param>
/// <returns></returns>
public int ExecuteSql(string sql, params object[] parameters)
{
return Context.Database.ExecuteSqlCommand(sql, parameters);
}
public int QueryCountSql(string sql, params object[] parameters)
{
try
{
return Context.Database.SqlQuery<int>(sql, parameters).FirstOrDefault(); }
catch (Exception ex)
{ throw ex;
}
} public DataTable FindDataTable(string sql)
{
OracleConnection conn = new OracleConnection();
conn.ConnectionString = Context.Database.Connection.ConnectionString;
if (conn.State != ConnectionState.Open)
{
conn.Open();
}
OracleCommand cmd = new OracleCommand();
cmd.Connection = conn;
cmd.CommandText = sql;
OracleDataAdapter adapter = new OracleDataAdapter(cmd);
DataTable table = new DataTable();
adapter.Fill(table);
conn.Close();//连接需要关闭
conn.Dispose();
return table; }
public DataTable SqlQueryForDataTatable(string sql, DbParameter[] parameters)
{
OracleConnection conn = new OracleConnection();
conn.ConnectionString = Context.Database.Connection.ConnectionString;
if (conn.State != ConnectionState.Open)
{
conn.Open();
}
OracleCommand cmd = new OracleCommand();
cmd.Connection = conn;
cmd.CommandText = sql; if (parameters != null && parameters.Length > )
{
foreach (var item in parameters)
{
cmd.Parameters.Add(item);
}
} OracleDataAdapter adapter = new OracleDataAdapter(cmd);
DataTable table = new DataTable();
adapter.Fill(table);
return table;
} /// <summary>
/// sql对象查询
/// </summary>
/// <param name="sql"></param>
/// <param name="parameters"></param>
/// <returns></returns>
public IEnumerable<TEntity> QuerySql(string sql, params object[] parameters)
{
try
{
return Context.Database.SqlQuery<TEntity>(sql, parameters).ToList(); }
catch (Exception ex)
{ throw ex;
} } /// <summary>
/// 删除所有
/// </summary>
public void DeleteAll()
{
Context.Models.RemoveRange(Context.Models);
} /// <summary>
/// 插入或更新
/// </summary>
/// <param name="entity"></param>
public void InsertOrUpdate(string keyValue, TEntity entity)
{
if (!string.IsNullOrEmpty(keyValue))
{
entity.Modify(keyValue);
Update(keyValue, entity);
}
else
{
entity.Create();
Context.Models.Add(entity);
}
}
/// <summary>
/// 批量插入
/// </summary>
/// <param name="list"></param>
public void InsertALL(List<TEntity> list)
{
Context.Models.AddRange(list);
Context.SaveChanges();
} /// <summary>
/// 保存修改
/// </summary>
public void SaveChanges()
{
Context.SaveChanges();
} /// <summary>
/// 销毁方法
/// </summary>
public void Dispose()
{
Context.SaveChanges();
Context.Dispose();
}
#endregion
#region 查询调用方法
/// <summary>
/// 分页查询 + 排序
/// </summary>
/// <typeparam name="Tkey">泛型</typeparam>
/// <param name="pageSize">每页大小</param>
/// <param name="pageIndex">当前页码</param>
/// <param name="total">总数量</param>
/// <param name="orderbyLambda">排序条件</param>
/// <param name="isAsc">是否升序</param>
/// <returns>IQueryable 泛型集合</returns>
public IQueryable<TEntity> FindList<Tkey>(int pageIndex, int pageSize, out int records, out int total, Func<TEntity, Tkey> orderbyLambda, bool isAsc)
{
records = Context.Set<TEntity>().Count(); if (records > )
{
total = records % pageSize == ? records / pageSize : records / pageSize + ;
}
else
{
total = ;
}
if (isAsc)
{
var temp = Context.Set<TEntity>()
.OrderBy<TEntity, Tkey>(orderbyLambda)
.Skip(pageSize * (pageIndex - ))
.Take(pageSize);
return temp.AsQueryable();
}
else
{
var temp = Context.Set<TEntity>()
.OrderByDescending<TEntity, Tkey>(orderbyLambda)
.Skip(pageSize * (pageIndex - ))
.Take(pageSize);
return temp.AsQueryable();
}
}
/// <summary>
/// 分页查询 + 条件查询 + 排序
/// </summary>
/// <typeparam name="Tkey">泛型</typeparam>
/// <param name="pageSize">每页大小</param>
/// <param name="pageIndex">当前页码</param>
/// <param name="total">总数量</param>
/// <param name="whereLambda">查询条件</param>
/// <param name="orderbyLambda">排序条件</param>
/// <param name="isAsc">是否升序</param>
/// <returns>IQueryable 泛型集合</returns>
public IQueryable<TEntity> FindList<Tkey>(int pageIndex, int pageSize, out int records, out int total, Expression<Func<TEntity, bool>> whereLambda, Func<TEntity, Tkey> orderbyLambda, bool isAsc)
{
records = Context.Set<TEntity>().Where(whereLambda).Count();
if (records > )
{
total = records % pageSize == ? records / pageSize : records / pageSize + ;
}
else
{
total = ;
}
if (isAsc)
{
var temp = Context.Set<TEntity>().Where(whereLambda)
.OrderBy<TEntity, Tkey>(orderbyLambda)
.Skip(pageSize * (pageIndex - ))
.Take(pageSize);
return temp.AsQueryable();
}
else
{
//降序
var temp = Context.Set<TEntity>().Where(whereLambda)
.OrderByDescending<TEntity, Tkey>(orderbyLambda)
.Skip(pageSize * (pageIndex - ))
.Take(pageSize);
return temp.AsQueryable();
}
}
#endregion } /// <summary>
/// 通过代码配置数据库,避免需要修改app.config
/// </summary>
public class OracleConfiguration : DbConfiguration
{
public OracleConfiguration()
{
SetProviderServices("Oracle.ManagedDataAccess.Client", Oracle.ManagedDataAccess.EntityFramework.EFOracleProviderServices.Instance);
SetProviderFactory("Oracle.ManagedDataAccess.Client", OracleClientFactory.Instance);
SetDefaultConnectionFactory(new Oracle.ManagedDataAccess.EntityFramework.OracleConnectionFactory());
}
}
}

IRepository

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks; namespace DataBaseTest.DataBase
{
public interface IRepository<T> : IDisposable where T : BaseEntity
{ /// <summary>
/// 删除实体
/// </summary>
/// <param name="item"></param>
bool Delete(string keyValue);
/// <summary>
/// 删除所有
/// </summary>
void DeleteAll(); /// <summary>
/// 获取实体集合(延时结果集)
/// </summary>
/// <returns></returns>
IQueryable<T> GetModels(); /// <summary>
/// 根据主键获得实体
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
T Find(object id); /// <summary>
/// 执行SQL
/// </summary>
/// <param name="sql"></param>
/// <param name="param"></param>
/// <returns></returns>
int ExecuteSql(string sql, params object[] parameters); /// <summary>
/// SQL查询
/// </summary>
/// <param name="sql"></param>
/// <param name="parameters"></param>
/// <returns></returns>
IEnumerable<T> QuerySql(string sql, params object[] parameters); /// <summary>
/// 手动保存
/// </summary>
void SaveChanges(); /// <summary>
/// 添加或更新
/// </summary>
/// <param name="entity"></param>
void InsertOrUpdate(string keyValue, T entity); /// <summary>
///批量插入
/// </summary>
/// <param name="list"></param>
void InsertALL(List<T> list); /// <summary>
/// 根据条件查询
/// </summary>
IQueryable<T> FindList<Tkey>(Expression<Func<T, bool>> whereLambda, Func<T, Tkey> orderbyLambda, bool isAsc); /// <summary>
/// 分页查询 + 条件查询 + 排序
/// </summary>
IQueryable<T> FindList<Tkey>(Pagination pagination, Expression<Func<T, bool>> whereLambda, Func<T, Tkey> orderbyLambda,out int records, out int total); /// <summary>
/// 分页查询 + 排序
/// </summary>
IQueryable<T> FindList<Tkey>(Pagination pagination, Func<T, Tkey> orderbyLambda, out int records, out int total); /// <summary>
/// 获取统计个数
/// </summary>
/// <param name="sql"></param>
/// <param name="parameters"></param>
/// <returns></returns>
int QueryCountSql(string sql, params object[] parameters); DataTable FindDataTable(string sql);
DataTable SqlQueryForDataTatable(string sql, DbParameter[] parameters);
}
}

Pagination

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks; namespace DataBaseTest.DataBase
{
public class Pagination
{
public Pagination()
{
pageIndex = ;
pageSize = ;
isAsc = false;
}
/// <summary>
/// 每页条数
/// </summary>
public int pageSize { get; set; }
/// <summary>
/// 当前页
/// </summary>
public int pageIndex { get; set; }
/// <summary>
/// 排序列
/// </summary>
public string sidx { get; set; }
/// <summary>
/// 是否升序排列
/// </summary>
public bool isAsc { get; set; }
/// <summary>
/// 总记录数
/// </summary>
public int records { get; set; }
/// <summary>
/// 总页数
/// </summary>
public int total { get; set; } }
}

ProgramContext

using Oracle.ManagedDataAccess.Client;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.Common;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks; namespace DataBaseTest.DataBase
{
public class ProgramContext<T> : DbContext
where T : BaseEntity
{
#region 构造函数
public ProgramContext()
: this(CreateConnection("Program"))
{ } public ProgramContext(DbConnection conn)
: base(conn, false)
{ } public ProgramContext(string connectionString)
: this(Create(connectionString))
{ }
#endregion #region 内部方法
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.HasDefaultSchema(UserName.ToUpper());
base.OnModelCreating(modelBuilder);
} protected static OracleConnection CreateConnection(string connectionName)
{
OracleConnectionStringBuilder oracleBuilder = new OracleConnectionStringBuilder();
oracleBuilder.ConnectionString = ConfigurationManager.ConnectionStrings[connectionName].ConnectionString;
UserName = oracleBuilder.UserID;
OracleConnection conn = new OracleConnection(oracleBuilder.ConnectionString);
return conn;
} protected static OracleConnection Create(string connectionString)
{
OracleConnectionStringBuilder oracleBuilder = new OracleConnectionStringBuilder();
oracleBuilder.ConnectionString = connectionString;
UserName = oracleBuilder.UserID;
OracleConnection conn = new OracleConnection(oracleBuilder.ConnectionString);
return conn;
}
#endregion #region 属性
public DbSet<T> Models { get; set; } private static string UserName { get; set; }
#endregion
}
}

RepositoryManager

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks; namespace DataBaseTest.DataBase
{
public class RepositoryManager
{
/// <summary>
/// 静态构造函数
/// </summary>
static RepositoryManager()
{
Connections = new Dictionary<string, string>();
} /// <summary>
/// 连接信息字典
/// </summary>
private static Dictionary<string, string> Connections { get; set; } /// <summary>
/// 默认创建方式
/// </summary>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
public static IRepository<T> CreateRepository<T>() where T : BaseEntity
{
try
{
return new EFRepository<T>(Connections["Program"]);
}
catch (KeyNotFoundException)
{
return new EFRepository<T>();
}
} /// <summary>
/// 指定连接信息创建方式
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="connectionString"></param>
/// <returns></returns>
public static IRepository<T> CreateRepository<T>(string name) where T : BaseEntity
{
try
{
return new EFRepository<T>(Connections[name]);
}
catch (KeyNotFoundException)
{
return new EFRepository<T>();
}
} /// <summary>
/// 添加链接信息
/// </summary>
/// <param name="name"></param>
/// <param name="connectionString"></param>
public static void AddConnection(string name, string connectionString)
{
if (Connections.ContainsKey(name))
Connections[name] = connectionString;
else
Connections.Add(name, connectionString);
}
}
}

oracle通用帮助类的更多相关文章

  1. C#操作SqlServer MySql Oracle通用帮助类

    C#操作SqlServer MySql Oracle通用帮助类 [前言] 作为一款成熟的面向对象高级编程语言,C#在ADO.Net的支持上已然是做的很成熟,我们可以方便地调用ADO.Net操作各类关系 ...

  2. C#操作SqlServer MySql Oracle通用帮助类Db_Helper_DG(默认支持数据库读写分离、查询结果实体映射ORM)

    [前言] 作为一款成熟的面向对象高级编程语言,C#在ADO.Net的支持上已然是做的很成熟,我们可以方便地调用ADO.Net操作各类关系型数据库,在使用了多年的Sql_Helper_DG后,由于项目需 ...

  3. oracle调用JAVA类的方法

    导入jar包 在oracle中导入需要的jar包,我们把编辑好的java类打成jar包,直接在oarcle里面写简单的调用就可以了,  1.操作系统需要拥有支持loadjava命令的jdk.  2.加 ...

  4. 一个操作oracle的c#类 含分页

    有别于以前的一个OracleHelper,这个版各有所长,MARK下. using System; using System.Data; using System.Data.OracleClient; ...

  5. [.net 面向对象程序设计进阶] (13) 序列化(Serialization)(五) Json 序列化利器 Newtonsoft.Json 及 通用Json类

    [.net 面向对象程序设计进阶] (13) 序列化(Serialization)(五) Json 序列化利器 Newtonsoft.Json 及 通用Json类 本节导读: 关于JSON序列化,不能 ...

  6. [.net 面向对象程序设计进阶] (11) 序列化(Serialization)(三) 通过接口 IXmlSerializable 实现XML序列化 及 通用XML类

    [.net 面向对象程序设计进阶] (11) 序列化(Serialization)(三) 通过接口 IXmlSerializable 实现XML序列化 及 通用XML类 本节导读:本节主要介绍通过序列 ...

  7. 通用窗口类 Inventory Pro 2.1.2 Demo1(下续篇 ),物品消耗扇形显示功能

    本篇想总结的是Inventory Pro中通用窗口的具体实现,但还是要强调下该插件的重点还是装备系统而不是通用窗口系统,所以这里提到的通用窗口类其实是通用装备窗口类(其实该插件中也有非装备窗口比如No ...

  8. 通用窗口类 Inventory Pro 2.1.2 Demo1(下)

    本篇想总结的是Inventory Pro中通用窗口的具体实现,但还是要强调下该插件的重点还是装备系统而不是通用窗口系统,所以这里提到的通用窗口类其实是通用装备窗口类(其实该插件中也有非装备窗口比如No ...

  9. 通用窗口类 Inventory Pro 2.1.2 Demo1(中)

    本篇想总结的是Inventory Pro中通用窗口的具体实现,但还是要强调下该插件的重点还是装备系统而不是通用窗口系统,所以这里提到的通用窗口类其实是通用装备窗口类(其实该插件中也有非装备窗口比如No ...

随机推荐

  1. PAT T1021 Safe Fruit

    暴力搜索加剪枝~ #include<bits/stdc++.h> using namespace std; ; const int inf=1e9; int g[maxn][maxn]; ...

  2. 六 Spring属性注入的四种方式:set方法、构造方法、P名称空间、SPEL表达式

    Spring的属性注入: 构造方法的属性注入 set方法的属性注入

  3. 列举出给定数量的字符的所有组成情况-java实现

    老早以前刚学程序的时候碰到了这么个问题,当时没想出来,今天突然想起来了这么个问题于是写了下,也算留个纪念吧 public static String itr; public static void m ...

  4. 使用java实现二叉查找树的插入,修改和删除方法

    目前使用的是根据key的hashcode来进行排序,并且没有考虑hash碰撞的问题 package com.zhou.tree; import java.util.Comparator; import ...

  5. 最近公共祖先(LCA)问题

    目录 最近公共祖先 1.向上标记法 2.树上倍增法 3.Tarjan算法 最近公共祖先 定义:给定一颗有根树,若结点 z 既是 x 的祖先,也是 y 的祖先,则称 z 是 x,y 的公共祖先.在 x, ...

  6. Linux命令:vmstat命令

    vmstat:虚拟内存状态查看命令 命令选项 vmstat 1         #每秒钟刷新1次 vmstat 1 3      #每秒刷新1次,只刷3次 vmstat -s        #显示内存 ...

  7. 使用 CocoaPods 遇到的问题记录

    1. 在 Terminal 输入 Cocoapods 命令时,有时会一直等待,出现“Performing a deep fetch of the `master` specs repo to impr ...

  8. C语言调试器GDB和LLDB的使用方法

    调试器的使用 编译输出带调试信息的程序 调试信息包含:指令地址.对应源代码及行号 指令完成后,回调 LINUX使用GDB MAX使用LLDB 使用说明 // 开始调试testlib程序 lldb te ...

  9. SQLite、MySQL和PostgreSQL 三种关系数据库哪个好?

    关系型数据库的使用已经有相当长的时间了.它们变得流行起来托了管理系统的福,关系模型被实现得相当的好,并且被证明是操作数据的好方法(特别是事务性强的应用). 在这篇DigitalOcean文章中,我们将 ...

  10. Swift-关于Swift编程语言

    一.首先让我们看看苹果公司是怎么描述自己的Swift的: Swift 是编写程序的绝佳选择,无论是手机.电脑还是服务器,任何能跑代码的设备都是如此.它是一门集现代语言之大成,集结了苹果的工程师文化精髓 ...