sql:
CREATE TABLE [PotoUsers] ( [UserID] INT IDENTITY(1,1) PRIMARY KEY, [UserName] NVARCHAR(50), [FirstName] NVARCHAR(50), [LastName] NVARCHAR(50), [MiddleName] NVARCHAR(50), [EmailID] NVARCHAR(50), [Adddate] datetime ) GO
/// <summary> /// 20180212 /// Entity /// 涂聚文 /// </summary> //[Table("PotoUsers")] public class PotoUsers { /// <summary> /// /// </summary> //[Key] public int UserID { get; set; } /// <summary> /// /// </summary> public string UserName { get; set; } /// <summary> /// /// </summary> public string FirstName { get; set; } /// <summary> /// /// </summary> public string LastName { get; set; } /// <summary> /// /// </summary> public string MiddleName { get; set; } /// <summary> /// /// </summary> public string FullName { get { return string.Format("{0} {1} {2}", FirstName,MiddleName, LastName); } } /// <summary> /// /// </summary> public string EmailID { get; set; } /// <summary> /// /// </summary> public DateTime Adddate { get; set; } }
/// <summary> /// 涂聚文 /// 20180212 /// </summary> public static class Mappings { public static void Initialize() { DapperExtensions.DapperExtensions.DefaultMapper = typeof(PluralizedAutoClassMapper<>); DapperExtensions.DapperExtensions.SetMappingAssemblies(new[] { typeof(Mappings).Assembly }); } /// <summary> /// /// </summary> public class PotoUsersMapper : ClassMapper<PotoUsers> { /// <summary> /// /// </summary> public PotoUsersMapper() { Table("PotoUsers"); //DuPotoUsers Map(Ducel => Ducel.UserID).Column("UserID").Key(KeyType.Identity); //主键类型 Map(Ducel => Ducel.UserName).Column("UserName"); Map(Ducel => Ducel.FirstName).Column("FirstName"); Map(Ducel => Ducel.LastName).Column("LastName"); Map(Ducel => Ducel.MiddleName).Column("MiddleName"); Map(Ducel => Ducel.EmailID).Column("EmailID"); Map(Ducel => Ducel.Adddate).Column("Adddate"); Map(Ducel => Ducel.FullName).Ignore(); AutoMap(); } } }
string connStr = System.Configuration.ConfigurationManager.ConnectionStrings["conDuString"].ToString(); /// <summary> /// /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { try { using (SqlConnection cn = new SqlConnection(connStr)) { //1获取值 //cn.Open(); //int UserID = 1; //PotoUsers potoUsers = cn.Get<PotoUsers>(UserID); //cn.Close(); //Response.Write(person.UserName); //2插入值 //cn.Open(); //PotoUsers potoUsers = new PotoUsers { UserName = "geovindu", MiddleName = "", EmailID = "geovindu@163.com", FirstName = "Foo", LastName = "Bar", Adddate = DateTime.Now }; //int id = cn.Insert(person); //cn.Close(); //3 修改 //cn.Open(); //int UserID = 1; //PotoUsers potoUsers = cn.Get<PotoUsers>(UserID); //potoUsers.UserName = "涂聚文"; //potoUsers.LastName = "du"; //potoUsers.FirstName = "geovin"; //cn.Update(potoUsers); //cn.Close(); //4.删除 //cn.Open(); //int UserID = 1; //PotoUsers potoUsers = cn.Get<PotoUsers>(UserID); //cn.Delete(potoUsers); //cn.Close(); //5. cn.Open(); var predicate = Predicates.Field<PotoUsers>(f => f.UserID, Operator.Like, true); IEnumerable<PotoUsers> list = cn.GetList<PotoUsers>(predicate); cn.Close(); Response.Write(list.ToList<PotoUsers>().Count.ToString()); } } catch (SqlException ex) { Response.Write(ex.Message.ToString()); } } }
https://github.com/zzzprojects/Dapper-Plus
https://github.com/tmsmith/Dapper-Extensions
https://github.com/ericdc1/Dapper.SimpleCRUD
http://www.bradoncode.com/blog/2012/12/creating-data-repository-using-dapper.html
https://github.com/bbraithwaite/RepoWrapper
https://github.com/bbraithwaite/SmsQuiz
https://github.com/henkmollema/Dapper-FluentMap
https://github.com/alexander-87/Dapper.FluentColumnMapping
https://github.com/StackExchange/Dapper/
https://github.com/ServiceStack/ServiceStack.OrmLite
https://github.com/senjacob/dapper-dot-net
https://github.com/senjacob/StackExchange.Redis
https://www.codeproject.com/tips/1030126/dapper-net-and-dapperextensions-to-run-stored-proc
/// <summary> /// 类型DuCoronavirusType表的实体类 ///生成時間2020/4/18 12:27:47 ///塗聚文(Geovin Du) ///</summary> public class DuCoronavirusTypeInfo { private int _CoronaviruTypeId; ///<summary> /// Id; ///</summary> public int CoronaviruTypeId { get { return _CoronaviruTypeId; } set {_CoronaviruTypeId = value; } } private string _CoronaviruTypeName; ///<summary> /// 类型名称; ///</summary> public string CoronaviruTypeName { get { return _CoronaviruTypeName; } set {_CoronaviruTypeName = value; } } private List<DuCoronavirusInfo> _DuCoronavirus; /// <summary> /// 主表:DuCoronavirusType类型,外键表:DuCoronavirus各类型最后更新数据表,外键字段:CoronaviruTypeKey; ///</summary> public List<DuCoronavirusInfo> DuCoronavirusList { get { return _DuCoronavirus; } set {_DuCoronavirus = value; } } private DataTable _DuCoronavirusData; /// <summary> /// 主表:DuCoronavirusType类型,外键表:DuCoronavirus各类型最后更新数据表,外键字段:CoronaviruTypeKey; ///</summary> public DataTable DuCoronavirusData { get { return _DuCoronavirusData; } set {_DuCoronavirusData = value; } } private DataSet _DuCoronavirusDaset; /// <summary> /// 主表:DuCoronavirusType类型,外键表:DuCoronavirus各类型最后更新数据表,外键字段:CoronaviruTypeKey; ///</summary> public DataSet DuCoronavirusDaset { get { return _DuCoronavirusDaset; } set {_DuCoronavirusDaset = value; } } }
/// <summary> /// 类型DuCoronavirusType表的实体类Mapping ///生成時間2020/4/18 12:27:47 ///塗聚文(Geovin Du) /// </summary> public class DuCoronavirusTypeMapping : ClassMapper<DuCoronavirusTypeInfo> { /// <summary> /// /// </summary> public DuCoronavirusTypeMapping() { Table("DuCoronavirusType"); Map(Ducel => Ducel.CoronaviruTypeId).Column("CoronaviruTypeId").Key(KeyType.Identity); //主键类型 Map(Ducel => Ducel.CoronaviruTypeName).Column("CoronaviruTypeName"); Map(Ducel => Ducel.DuCoronavirusDaset).Ignore(); Map(Ducel => Ducel.DuCoronavirusData).Ignore(); Map(Ducel => Ducel.DuCoronavirusList).Ignore(); AutoMap(); } }
/// <summary> /// 插入有返回ID的值 ? /// List之Union(),Intersect(),Except() 即并集,交集,差集运算 /// Linq常用List操作总结,ForEach、分页、交并集、去重、SelectMany等 /// geovindu /// </summary> public class PotoUsersDAL:IPotoUsers { /// <summary> /// /// </summary> string connStr = System.Configuration.ConfigurationManager.ConnectionStrings["conDuString"].ToString(); int commandTimeout = 3000; /// <summary> /// /// </summary> public PotoUsersDAL() { } /// <summary> /// ID查找一条记录 /// </summary> /// <param name="userId"></param> /// <returns></returns> public PotoUsers InfoId(int userId) { PotoUsers potoUsers = new PotoUsers(); using (SqlConnection cn = new SqlConnection(connStr)) { cn.Open(); //int UserID = userId; potoUsers = cn.Get<PotoUsers>(userId); cn.Close(); } return potoUsers; } /// <summary> /// /// </summary> /// <param name="username"></param> /// <returns></returns> public PotoUsers InfoName(string username) { PotoUsers potoUsers = new PotoUsers(); using (SqlConnection cn = new SqlConnection(connStr)) { cn.Open(); potoUsers = cn.GetList<PotoUsers>(new { UserName=username }).FirstOrDefault(); //potoUsers = cn.Query<PotoUsers>(sql, new { UserName = username }).FirstOrDefault(); cn.Close(); } return potoUsers; } /// <summary> /// /// </summary> /// <param name="stname"></param> /// <returns></returns> public PotoUsers select(string stname) { //https://github.com/tmsmith/Dapper-Extensions/wiki/Predicates //https://stackoverflow.com/questions/16083895/grouping-lambda-expressions-by-operators-and-using-them-with-dapperextensions-p var predicateGroupAnd = new PredicateGroup { Operator = GroupOperator.And, Predicates = new List<IPredicate>() }; //// I already have the code to determine: left = p => p.MarketId, theOperator = Operator.Eq, right = marketId //predicateGroupAnd.Predicates.Add(Predicates.Field(left, Operator.Eq, right)); //var predicateGroupOr = new PredicateGroup {Operator = GroupOperator.Or, Predicates = new List<IPredicate>()}; //// I already have the code to determine: left = p => p.FirstName, theOperator = Operator.Eq, right = "John" //predicateGroupAnd.Predicates.Add(Predicates.Field(left, Operator.Eq, right)); //// I already have the code to determine: left = p => p.FirstName, theOperator = Operator.Eq, right = "Jack" //predicateGroupOr.Predicates.Add(Predicates.Field(left, Operator.Eq, right)); //var predicateGroupAll = new PredicateGroup // This is what will be passed to DapperExtensions' GetList<T> method // { // Operator = GroupOperator.And, // How do I set this correctly? // Predicates = new List<IPredicate> {predicateGroupAnd, predicateGroupOr} // }; var predicate = Predicates.Field<PotoUsers>(f => f.UserName, Operator.Eq, stname); predicateGroupAnd.Predicates.Add(predicate); PotoUsers user = SqlHelper.Find<PotoUsers>(predicateGroupAnd); return user; } /// <summary> /// /// </summary> /// <param name="stname"></param> /// <param name="lastrname"></param> /// <returns></returns> public List<PotoUsers> selectAndList(string stname,string lastrname) { using (SqlConnection cn = new SqlConnection(connStr)) { cn.Open(); var pg = new PredicateGroup { Operator = GroupOperator.And, Predicates = new List<IPredicate>() }; pg.Predicates.Add(Predicates.Field<PotoUsers>(f => f.UserName, Operator.Eq, stname)); pg.Predicates.Add(Predicates.Field<PotoUsers>(f => f.LastName, Operator.Eq, lastrname)); IEnumerable<PotoUsers> list =cn.GetList<PotoUsers>(pg); cn.Close(); return list.ToList(); } } /// <summary> /// /// </summary> /// <param name="stname"></param> /// <param name="lastrname"></param> /// <returns></returns> public PotoUsers selectAnd(string stname, string lastrname) { var pg = new PredicateGroup { Operator = GroupOperator.And, Predicates = new List<IPredicate>() }; pg.Predicates.Add(Predicates.Field<PotoUsers>(f => f.UserName, Operator.Eq, stname)); pg.Predicates.Add(Predicates.Field<PotoUsers>(f => f.LastName, Operator.Eq, lastrname)); return SqlHelper.Find<PotoUsers>(pg, connStr); } /// <summary> /// 插入返回ID /// </summary> /// <param name="inf"></param> /// <returns></returns> public int InsertOut(PotoUsers inf) { int recordId = 0; PotoUsers sele = null; sele=InfoName(inf.UserName); if (object.Equals(sele, null)) { recordId = SqlHelper.InsertWithReturnId(inf); //返回就是ID } return recordId; } /// <summary> /// 插入 /// </summary> /// <param name="inf"></param> /// <returns></returns> public bool Insert(PotoUsers inf) { bool recordId = false; PotoUsers sele = null; sele=InfoName(inf.UserName); if (object.Equals(sele, null)) { recordId = SqlHelper.Insert(inf); } return recordId; } /// <summary> /// 添加 /// </summary> /// <param name="inf"></param> /// <returns></returns> public int Add(PotoUsers inf) { int id = 0; PotoUsers sele = null; using (SqlConnection cn = new SqlConnection(connStr)) { cn.Open(); // PotoUsers potoUsers = new PotoUsers { UserName = inf.UserName, MiddleName = inf.MiddleName, EmailID = inf.EmailID, FirstName =inf.FirstName, LastName = inf.LastName, Adddate = DateTime.Now }; //查找没有同名称的再添加,否则不添加 sele=InfoName(inf.UserName); if (object.Equals(sele, null)) { id = cn.Insert(inf); //返回的是ID } cn.Close(); } return id; } /// <summary> /// 插入返回ID /// </summary> /// <param name="inf"></param> /// <param name="Id"></param> /// <returns></returns> public int AddOut(PotoUsers inf,out int Id) { int k = 0; int id = 0; using (SqlConnection cn = new SqlConnection(connStr)) { cn.Open(); using (var trans = cn.BeginTransaction()) { try { k = cn.Insert(inf, trans, commandTimeout); //没有插入成功 // string sql = "SELECT @@IDENTITY AS Id"; id = k;// cn.Query(sql).Single(); } catch (Exception ex) { ex.Message.ToString(); trans.Rollback(); cn.Close(); } Id = id; } cn.Close(); } return k; } /// <summary> /// 插入多条 /// </summary> /// <param name="infs"></param> /// <returns></returns> public int AddMore(List<PotoUsers> infs) { int id = 0; using (SqlConnection cn = new SqlConnection(connStr)) { cn.Open(); using (var trans = cn.BeginTransaction()) { // PotoUsers potoUsers = new PotoUsers { UserName = inf.UserName, MiddleName = inf.MiddleName, EmailID = inf.EmailID, FirstName =inf.FirstName, LastName = inf.LastName, Adddate = DateTime.Now }; id = cn.Insert(infs, trans, commandTimeout); } cn.Close(); } return id; } /// <summary> /// 修改 /// </summary> /// <param name="inf"></param> /// <returns></returns> public int Update(PotoUsers inf) { int id = 0; using (SqlConnection cn = new SqlConnection(connStr)) { cn.Open(); //int UserID = inf.UserID; //PotoUsers potoUsers = cn.Get<PotoUsers>(UserID); //potoUsers.UserName = inf.UserName; //potoUsers.LastName = inf.LastName; //potoUsers.FirstName = inf.FirstName; //potoUsers.MiddleName = inf.MiddleName; //potoUsers.EmailID = inf.EmailID; //potoUsers.Adddate = DateTime.Now; cn.Update(inf); cn.Close(); } return id; } /// <summary> /// /// </summary> /// <param name="inf"></param> /// <returns></returns> public bool edit(PotoUsers inf) { bool ok = false; PotoUsers sele = null; sele = InfoName(inf.UserName); if(object.Equals(sele,null)) ok = SqlHelper.Update<PotoUsers>(inf); return ok; } /// <summary> /// /// </summary> /// <param name="userID"></param> /// <returns></returns> public bool Del(int userID) { bool id = false; using (SqlConnection cn = new SqlConnection(connStr)) { cn.Open(); //int UserID = 1; PotoUsers potoUsers = cn.Get<PotoUsers>(userID); id=cn.Delete(potoUsers); cn.Close(); } return id; } /// <summary> /// /// </summary> /// <returns></returns> public List<PotoUsers> InfoAll() { IEnumerable<PotoUsers> list = null; using (SqlConnection cn = new SqlConnection(connStr)) { cn.Open(); //var predicate = Predicates.Field<PotoUsers>(f => f.UserID, Operator.Like, true); //list = cn.GetList<PotoUsers>(predicate); list = cn.GetList<PotoUsers>(); cn.Close(); } return list.ToList<PotoUsers>(); } }
/// <summary> /// geovindu /// 20200417 /// 涂聚文 /// </summary> public static class SqlHelper { public static string ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["conDuString"].ConnectionString; /// <summary> /// /// </summary> private static string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["conDuString"].ConnectionString; ////@"Data Source=GEOVINDU-PC;Initial Catalog=DuMailSystem;Integrated Security=True;uid=sa;pwd=88888"; /// <summary> /// Gets the open connection. /// </summary> /// <param name="name">The name of the connection string (optional).</param> /// <returns></returns> public static SqlConnection GetOpenConnection() { connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["conDuString"].ConnectionString; // string connString = ""; //connString = name == null ? connString = ConfigurationManager.ConnectionStrings[0].ConnectionString : connString = ConfigurationManager.ConnectionStrings[name].ConnectionString; var connection = new SqlConnection(connectionString); connection.Open(); return connection; } /// <summary> /// /// </summary> /// <typeparam name="T"></typeparam> /// <param name="parameter"></param> /// <param name="connectionString"></param> /// <returns></returns> public static bool Insert<T>(T parameter, string connectionString) where T : class { using (var sqlConnection = new SqlConnection(connectionString)) { sqlConnection.Open(); sqlConnection.Insert(parameter); sqlConnection.Close(); return true; } } /// <summary> /// /// </summary> /// <typeparam name="T"></typeparam> /// <param name="parameter"></param> /// <returns></returns> public static bool Insert<T>(T parameter) where T : class { using (var sqlConnection = new SqlConnection(connectionString)) { sqlConnection.Open(); sqlConnection.Insert(parameter); sqlConnection.Close(); return true; } } /// <summary> /// /// </summary> /// <typeparam name="T"></typeparam> /// <param name="parameter"></param> /// <param name="connectionString"></param> /// <returns></returns> public static int InsertWithReturnId<T>(T parameter, string connectionString) where T : class { using (var sqlConnection = new SqlConnection(connectionString)) { sqlConnection.Open(); var recordId = sqlConnection.Insert(parameter); sqlConnection.Close(); return recordId; } } /// <summary> /// /// </summary> /// <typeparam name="T"></typeparam> /// <param name="parameter"></param> /// <returns></returns> public static int InsertWithReturnId<T>(T parameter) where T : class { using (var sqlConnection = new SqlConnection(connectionString)) { sqlConnection.Open(); var recordId = sqlConnection.Insert(parameter); sqlConnection.Close(); return recordId; } } /// <summary> /// /// </summary> /// <typeparam name="T"></typeparam> /// <param name="parameter"></param> /// <param name="connectionString"></param> /// <returns></returns> public static bool Update<T>(T parameter, string connectionString) where T : class { using (var sqlConnection = new SqlConnection(connectionString)) { sqlConnection.Open(); sqlConnection.Update(parameter); sqlConnection.Close(); return true; } } /// <summary> /// /// </summary> /// <typeparam name="T"></typeparam> /// <param name="parameter"></param> /// <returns></returns> public static bool Update<T>(T parameter) where T : class { using (var sqlConnection = new SqlConnection(connectionString)) { sqlConnection.Open(); sqlConnection.Update(parameter); sqlConnection.Close(); return true; } } /// <summary> /// /// </summary> /// <typeparam name="T"></typeparam> /// <param name="connectionString"></param> /// <returns></returns> public static IList<T> GetAll<T>(string connectionString) where T : class { using (var sqlConnection = new SqlConnection(connectionString)) { sqlConnection.Open(); var result = sqlConnection.GetList<T>(); sqlConnection.Close(); return result.ToList(); } } /// <summary> /// /// </summary> /// <typeparam name="T"></typeparam> /// <returns></returns> public static IList<T> GetAll<T>() where T : class { using (var sqlConnection = new SqlConnection(connectionString)) { sqlConnection.Open(); var result = sqlConnection.GetList<T>(); sqlConnection.Close(); return result.ToList(); } } /// <summary> /// /// </summary> /// <typeparam name="T"></typeparam> /// <param name="predicate"></param> /// <param name="connectionString"></param> /// <returns></returns> public static T Find<T>(PredicateGroup predicate, string connectionString) where T : class { using (var sqlConnection = new SqlConnection(connectionString)) { sqlConnection.Open(); var result = sqlConnection.GetList<T>(predicate).FirstOrDefault(); sqlConnection.Close(); return result; } } /// <summary> /// /// </summary> /// <typeparam name="T"></typeparam> /// <param name="predicate"></param> /// <returns></returns> public static T Find<T>(PredicateGroup predicate) where T : class { using (var sqlConnection = new SqlConnection(connectionString)) { sqlConnection.Open(); var result = sqlConnection.GetList<T>(predicate).FirstOrDefault(); sqlConnection.Close(); return result; } } /// <summary> /// /// </summary> /// <typeparam name="T"></typeparam> /// <param name="predicate"></param> /// <param name="connectionString"></param> /// <returns></returns> public static bool Delete<T>(PredicateGroup predicate, string connectionString) where T : class { using (var sqlConnection = new SqlConnection(connectionString)) { sqlConnection.Open(); sqlConnection.Delete<T>(predicate); sqlConnection.Close(); return true; } } /// <summary> /// /// </summary> /// <typeparam name="T"></typeparam> /// <param name="predicate"></param> /// <returns></returns> public static bool Delete<T>(PredicateGroup predicate) where T : class { using (var sqlConnection = new SqlConnection(connectionString)) { sqlConnection.Open(); sqlConnection.Delete<T>(predicate); sqlConnection.Close(); return true; } } /// <summary> /// /// </summary> /// <typeparam name="T"></typeparam> /// <param name="storedProcedure"></param> /// <param name="param"></param> /// <param name="outParam"></param> /// <param name="transaction"></param> /// <param name="buffered"></param> /// <param name="commandTimeout"></param> /// <param name="connectionString"></param> /// <returns></returns> public static IEnumerable<T> QuerySP<T>(string storedProcedure, dynamic param = null, dynamic outParam = null, SqlTransaction transaction = null, bool buffered = true, int? commandTimeout = null, string connectionString = null) where T : class { SqlConnection connection = new SqlConnection(connectionString); connection.Open(); var output = connection.Query<T>(storedProcedure, param: (object)param, transaction: transaction, buffered: buffered, commandTimeout: commandTimeout, commandType: CommandType.StoredProcedure); return output; } /// <summary> /// /// </summary> /// <typeparam name="T"></typeparam> /// <param name="storedProcedure"></param> /// <param name="param"></param> /// <param name="outParam"></param> /// <param name="transaction"></param> /// <param name="buffered"></param> /// <param name="commandTimeout"></param> /// <returns></returns> public static IEnumerable<T> QuerySP<T>(string storedProcedure, dynamic param = null, dynamic outParam = null, SqlTransaction transaction = null, bool buffered = true, int? commandTimeout = null) where T : class { SqlConnection connection = new SqlConnection(connectionString); connection.Open(); var output = connection.Query<T>(storedProcedure, param: (object)param, transaction: transaction, buffered: buffered, commandTimeout: commandTimeout, commandType: CommandType.StoredProcedure); return output; } /// <summary> /// /// </summary> /// <param name="param"></param> /// <param name="outParam"></param> private static void CombineParameters(ref dynamic param, dynamic outParam = null) { if (outParam != null) { if (param != null) { param = new DynamicParameters(param); ((DynamicParameters)param).AddDynamicParams(outParam); } else { param = outParam; } } } /// <summary> /// /// </summary> private static int ConnectionTimeout { get; set; } /// <summary> /// /// </summary> /// <param name="commandTimeout"></param> /// <returns></returns> private static int GetTimeout(int? commandTimeout = null) { if (commandTimeout.HasValue) return commandTimeout.Value; return ConnectionTimeout; } }