EFRepositoryBase
using System; using System.Collections.Generic; using System.Data; using System.Data.Entity; using System.Data.SqlClient; using System.Linq; using System.Text; namespace Piano.Common.Extend.Models.DBProvider { public class EFRepositoryBase<T> where T : DbContext { protected T _ctx; /// <summary> /// 执行存储过程并返回returnValue值,适用于不返回结果集,只返回一个returnvalue的存储过程 /// </summary> /// <param name="storedProcedure"></param> /// <param name="parameters"></param> /// <returns></returns> public object ExecuteStoredProcedureNonQuery(string storedProcedure,string _conn_str, params SqlParameter[] parameters) { //string ConnectionString = _ctx.Database.Connection.ConnectionString; SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(_conn_str); builder.ConnectTimeout = 2500; object returnValue = null; using (SqlConnection con = new SqlConnection(builder.ConnectionString)) { con.Open(); using (SqlCommand cmd = con.CreateCommand()) { try { cmd.CommandText = storedProcedure; cmd.CommandType = System.Data.CommandType.StoredProcedure; cmd.CommandTimeout = 0; foreach (SqlParameter p in parameters) { cmd.Parameters.Add(p); } SqlParameter retval = new System.Data.SqlClient.SqlParameter { ParameterName = "@ReturnValue", }; retval.Direction = ParameterDirection.ReturnValue; cmd.Parameters.Add(retval); int rows = cmd.ExecuteNonQuery(); returnValue = cmd.Parameters["@ReturnValue"].Value; } catch (Exception e) { returnValue = -1; System.Diagnostics.Debug.WriteLine(e.StackTrace); } cmd.Dispose(); } con.Close(); } return returnValue; } } }
使用:
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Piano.Common.Extend.Models.DBProvider { public class FlowOrderRepository : EFRepositoryBase<PianoEntities> { public FlowOrderRepository() { _ctx = new PianoEntities(); } public void SaveOrder() { _ctx.SaveChanges(); } } }