├── src ├── Galaxy.Libra.DapperExtensions.Test │ ├── PredicatesUnitTest.cs │ ├── Entity │ │ ├── Role.cs │ │ ├── User.cs │ │ └── TestEntity.cs │ ├── Galaxy.Libra.DapperExtensions.Test.csproj │ ├── DBBuilderTest.cs │ ├── DapperExtensionsTest.cs │ ├── SqlGeneratorUnitTest.cs │ ├── TestEntityRepositoryTest.cs │ └── PredicateConverTest.cs ├── Galaxy.Libra.DapperExtensions │ ├── DBBuilder │ │ ├── IDataBaseBuilder.cs │ │ ├── IDBColumnConverter.cs │ │ ├── ITableBuilder.cs │ │ └── MySQL │ │ │ ├── Convert │ │ │ ├── MySQLBoolConvert.cs │ │ │ ├── MySQLEnumConvert.cs │ │ │ ├── MySQLLongConvert.cs │ │ │ ├── MySQLDateTimeConvert.cs │ │ │ ├── MySQLIntConvert.cs │ │ │ └── MySqlStringConverter.cs │ │ │ ├── MySQLDBBuilder.cs │ │ │ └── MySQLTableBuilder.cs │ ├── Predicate │ │ ├── Sort.cs │ │ ├── PropertyPredicate.cs │ │ ├── BasePredicate.cs │ │ ├── BetweenPredicate.cs │ │ ├── ExistsPredicate.cs │ │ ├── PredicateGroup.cs │ │ ├── FieldPredicate.cs │ │ ├── ComparePredicate.cs │ │ └── Predicates.cs │ ├── Mapper │ │ ├── AutoClassMapper.cs │ │ ├── PluralizedAutoClassMapper.cs │ │ ├── PropertyMap.cs │ │ └── ClassMapper.cs │ ├── Galaxy.Libra.DapperExtensions.csproj │ ├── DapperImpl │ │ ├── DapperImplementorGet.cs │ │ ├── DapperImplementor.cs │ │ ├── DapperImplementorUpdate.cs │ │ ├── DapperImplementorCount.cs │ │ ├── DapperImplementorGetList.cs │ │ ├── DapperImplementorGetPage.cs │ │ ├── DapperImplementorGetSet.cs │ │ ├── DapperImplementorDelete.cs │ │ ├── IDapperImplementor.cs │ │ ├── DapperImplementorGetMultiple.cs │ │ └── DapperImplementorInsert.cs │ ├── Galaxy.Libra.DapperExtensions.nuspec │ ├── GetMultipleResult.cs │ ├── Sql │ │ ├── MySqlDialect.cs │ │ ├── PostgreSqlDialect.cs │ │ ├── SqliteDialect.cs │ │ ├── SqlCeDialect.cs │ │ ├── SqlDialectBase.cs │ │ ├── SqlServerDialect.cs │ │ └── SqlGenerator.cs │ ├── PredicateConver │ │ ├── EntityPredicateConvert.cs │ │ ├── KeyPredicateConvert.cs │ │ ├── IdPredicateConvert.cs │ │ └── ExpressionPredicateConvert.cs │ ├── GetMultiplePredicate.cs │ ├── EntityRepository │ │ ├── IBaseEntityRepository.cs │ │ └── BaseEntityRepository.cs │ ├── ReflectionHelper.cs │ ├── DapperExtensionsConfiguration.cs │ ├── Database.cs │ └── DapperExtensions.cs └── Galaxy.Libra.DapperExtensions.sln ├── LICENSE ├── .gitattributes ├── README.md └── .gitignore /src/Galaxy.Libra.DapperExtensions.Test/PredicatesUnitTest.cs: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leeon201314/Galaxy.Libra.DapperExtensions/HEAD/src/Galaxy.Libra.DapperExtensions.Test/PredicatesUnitTest.cs -------------------------------------------------------------------------------- /src/Galaxy.Libra.DapperExtensions/DBBuilder/IDataBaseBuilder.cs: -------------------------------------------------------------------------------- 1 | namespace Galaxy.Libra.DapperExtensions.DBBuilder 2 | { 3 | public interface IDataBaseBuilder 4 | { 5 | void CreateDataBase(string dbName); 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /src/Galaxy.Libra.DapperExtensions/DBBuilder/IDBColumnConverter.cs: -------------------------------------------------------------------------------- 1 | using Galaxy.Libra.DapperExtensions.Mapper; 2 | 3 | namespace Galaxy.Libra.DapperExtensions.DBBuilder 4 | { 5 | public interface IDBColumnConverter 6 | { 7 | string Convert(IPropertyMap propertyMap); 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /src/Galaxy.Libra.DapperExtensions/DBBuilder/ITableBuilder.cs: -------------------------------------------------------------------------------- 1 | using Galaxy.Libra.DapperExtensions.Mapper; 2 | using System; 3 | 4 | namespace Galaxy.Libra.DapperExtensions.DBBuilder 5 | { 6 | public interface ITableBuilder 7 | { 8 | void CreateTable(Type t, IClassMapper classMap); 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /src/Galaxy.Libra.DapperExtensions/DBBuilder/MySQL/Convert/MySQLBoolConvert.cs: -------------------------------------------------------------------------------- 1 | using Galaxy.Libra.DapperExtensions.Mapper; 2 | 3 | namespace Galaxy.Libra.DapperExtensions.DBBuilder.MySQL.Convert 4 | { 5 | public class MySQLBoolConvert : IDBColumnConverter 6 | { 7 | public string Convert(IPropertyMap propertyMap) => "bool"; 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /src/Galaxy.Libra.DapperExtensions/DBBuilder/MySQL/Convert/MySQLEnumConvert.cs: -------------------------------------------------------------------------------- 1 | using Galaxy.Libra.DapperExtensions.Mapper; 2 | 3 | namespace Galaxy.Libra.DapperExtensions.DBBuilder.MySQL.Convert 4 | { 5 | public class MySQLEnumConvert : IDBColumnConverter 6 | { 7 | public string Convert(IPropertyMap propertyMap) => "int"; 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /src/Galaxy.Libra.DapperExtensions/DBBuilder/MySQL/Convert/MySQLLongConvert.cs: -------------------------------------------------------------------------------- 1 | using Galaxy.Libra.DapperExtensions.Mapper; 2 | 3 | namespace Galaxy.Libra.DapperExtensions.DBBuilder.MySQL.Convert 4 | { 5 | public class MySQLLongConvert : IDBColumnConverter 6 | { 7 | public string Convert(IPropertyMap propertyMap) => "bigint"; 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /src/Galaxy.Libra.DapperExtensions/DBBuilder/MySQL/Convert/MySQLDateTimeConvert.cs: -------------------------------------------------------------------------------- 1 | using Galaxy.Libra.DapperExtensions.Mapper; 2 | 3 | namespace Galaxy.Libra.DapperExtensions.DBBuilder.MySQL.Convert 4 | { 5 | public class MySQLDateTimeConvert : IDBColumnConverter 6 | { 7 | public string Convert(IPropertyMap propertyMap) => "datetime"; 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /src/Galaxy.Libra.DapperExtensions/Predicate/Sort.cs: -------------------------------------------------------------------------------- 1 | namespace Galaxy.Libra.DapperExtensions.Predicate 2 | { 3 | public interface ISort 4 | { 5 | string PropertyName { get; set; } 6 | bool Ascending { get; set; } 7 | } 8 | 9 | public class Sort : ISort 10 | { 11 | public string PropertyName { get; set; } 12 | public bool Ascending { get; set; } 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/Galaxy.Libra.DapperExtensions.Test/Entity/Role.cs: -------------------------------------------------------------------------------- 1 | using Galaxy.Libra.DapperExtensions.Mapper; 2 | 3 | namespace Galaxy.Libra.DapperExtensions.Test.Entity 4 | { 5 | public class Role 6 | { 7 | public string Id { get; set; } 8 | 9 | public string Name { get; set; } 10 | } 11 | 12 | public class RoleMapper : ClassMapper 13 | { 14 | public RoleMapper() 15 | { 16 | Table("Role"); 17 | AutoMap(); 18 | } 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/Galaxy.Libra.DapperExtensions/Mapper/AutoClassMapper.cs: -------------------------------------------------------------------------------- 1 | using System.Text; 2 | using System.Linq; 3 | using System.Collections.Generic; 4 | using System; 5 | 6 | namespace Galaxy.Libra.DapperExtensions.Mapper 7 | { 8 | /// 9 | /// Automatically maps an entity to a table using a combination of reflection and naming conventions for keys. 10 | /// 11 | public class AutoClassMapper : ClassMapper where T : class 12 | { 13 | public AutoClassMapper() 14 | { 15 | Type type = typeof(T); 16 | Table(type.Name); 17 | AutoMap(); 18 | } 19 | } 20 | } -------------------------------------------------------------------------------- /src/Galaxy.Libra.DapperExtensions/DBBuilder/MySQL/Convert/MySQLIntConvert.cs: -------------------------------------------------------------------------------- 1 | using Galaxy.Libra.DapperExtensions.Mapper; 2 | 3 | namespace Galaxy.Libra.DapperExtensions.DBBuilder.MySQL.Convert 4 | { 5 | public class MySQLIntConvert : IDBColumnConverter 6 | { 7 | public string Convert(IPropertyMap propertyMap) 8 | { 9 | if (propertyMap != null) 10 | { 11 | if (propertyMap.ColumnLength <= 0) 12 | return "int"; 13 | else 14 | return $"int({propertyMap.ColumnLength})"; 15 | } 16 | 17 | return "int"; 18 | } 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/Galaxy.Libra.DapperExtensions/Galaxy.Libra.DapperExtensions.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | netcoreapp2.2 5 | leeon 6 | 一个轻量的dapper扩展库 7 | leeon 8 | 1.0.0.1 9 | 1.0.0.1 10 | 1.0.5 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | -------------------------------------------------------------------------------- /src/Galaxy.Libra.DapperExtensions.Test/Entity/User.cs: -------------------------------------------------------------------------------- 1 | using Galaxy.Libra.DapperExtensions.Mapper; 2 | 3 | namespace Galaxy.Libra.DapperExtensions.Test.Entity 4 | { 5 | public class User 6 | { 7 | public int Id { get; set; } 8 | 9 | public string Name { get; set; } 10 | 11 | public string Psw { get; set; } 12 | 13 | public string RoleId { get; set; } 14 | 15 | public Role Role { get; set; } 16 | } 17 | 18 | public class UserMapper : ClassMapper 19 | { 20 | public UserMapper() 21 | { 22 | Table("UserTest"); 23 | Map(p => p.Id).Key(KeyType.Assigned); 24 | Map(p => p.Role).Ignore(); 25 | AutoMap(); 26 | } 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/Galaxy.Libra.DapperExtensions.Test/Entity/TestEntity.cs: -------------------------------------------------------------------------------- 1 | using Galaxy.Libra.DapperExtensions.Mapper; 2 | 3 | namespace Galaxy.Libra.DapperExtensions.Test.Entity 4 | { 5 | public class TestEntity 6 | { 7 | public int Id { get; set; } 8 | 9 | public string Name { get; set; } 10 | 11 | public int TestInt { get; set; } 12 | } 13 | 14 | public class TestEntityMapper : ClassMapper 15 | { 16 | public TestEntityMapper() 17 | { 18 | Table("TestTable"); 19 | Map(p => p.Id).Key(KeyType.Identity).AutoIncrement(); 20 | Map(p => p.TestInt).Length(4).Column("Test").Required(); 21 | Map(p => p.Name).Length(30).Required(); 22 | AutoMap(); 23 | } 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/Galaxy.Libra.DapperExtensions/DBBuilder/MySQL/Convert/MySqlStringConverter.cs: -------------------------------------------------------------------------------- 1 | using Galaxy.Libra.DapperExtensions.Mapper; 2 | 3 | namespace Galaxy.Libra.DapperExtensions.DBBuilder.MySQL.Convert 4 | { 5 | public class MySqlStringConverter : IDBColumnConverter 6 | { 7 | public string Convert(IPropertyMap propertyMap) 8 | { 9 | if (propertyMap != null) 10 | { 11 | if (propertyMap.ColumnLength == int.MaxValue) 12 | return "LONGTEXT"; 13 | else if (propertyMap.ColumnLength <= 0) 14 | return "varchar(255)"; 15 | else 16 | return $"varchar({propertyMap.ColumnLength})"; 17 | } 18 | 19 | return "varchar(255)"; 20 | } 21 | } 22 | } -------------------------------------------------------------------------------- /src/Galaxy.Libra.DapperExtensions.Test/Galaxy.Libra.DapperExtensions.Test.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | netcoreapp2.2 5 | 6 | false 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | -------------------------------------------------------------------------------- /src/Galaxy.Libra.DapperExtensions/DapperImpl/DapperImplementorGet.cs: -------------------------------------------------------------------------------- 1 | using Galaxy.Libra.DapperExtensions.Mapper; 2 | using Galaxy.Libra.DapperExtensions.Predicate; 3 | using Galaxy.Libra.DapperExtensions.PredicateConver; 4 | using System.Data; 5 | using System.Linq; 6 | 7 | namespace Galaxy.Libra.DapperExtensions.DapperImpl 8 | { 9 | public partial class DapperImplementor 10 | { 11 | public T Get(IDbConnection connection, dynamic id, IDbTransaction transaction, int? commandTimeout) where T : class 12 | { 13 | IClassMapper classMap = SqlGenerator.Configuration.GetMap(); 14 | IPredicate predicate = IdPredicateConvert.GetIdPredicate(classMap, id); 15 | T result = GetList(connection, classMap, predicate, null, transaction, commandTimeout, true).SingleOrDefault(); 16 | return result; 17 | } 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/Galaxy.Libra.DapperExtensions/Galaxy.Libra.DapperExtensions.nuspec: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | $id$ 5 | $version$ 6 | $title$ 7 | Leeon 8 | Leeon 9 | http://LICENSE_URL_HERE_OR_DELETE_THIS_LINE 10 | http://PROJECT_URL_HERE_OR_DELETE_THIS_LINE 11 | http://ICON_URL_HERE_OR_DELETE_THIS_LINE 12 | false 13 | a small library that complements Dapper by adding basic CRUD operations (Get, Insert, Update, Delete) for your POCOs. 14 | Summary of changes made in this release of the package. 15 | Copyright 2019 16 | Tag1 Tag2 17 | 18 | -------------------------------------------------------------------------------- /src/Galaxy.Libra.DapperExtensions/DBBuilder/MySQL/MySQLDBBuilder.cs: -------------------------------------------------------------------------------- 1 | using Dapper; 2 | using System.Data; 3 | 4 | namespace Galaxy.Libra.DapperExtensions.DBBuilder.MySQL 5 | { 6 | public class MySQLDBBuilder : IDataBaseBuilder 7 | { 8 | protected IDbConnection curDbConnection = null; 9 | 10 | public MySQLDBBuilder(IDbConnection dbConnection) 11 | { 12 | curDbConnection = dbConnection; 13 | } 14 | 15 | public void CreateDataBase(string dbName) 16 | { 17 | if (curDbConnection != null) 18 | { 19 | using (curDbConnection) 20 | { 21 | if (curDbConnection.State != ConnectionState.Open) 22 | curDbConnection.Open(); 23 | 24 | curDbConnection.Execute($"Create Database If Not Exists {dbName} Character Set utf8mb4;"); 25 | 26 | curDbConnection.Close(); 27 | } 28 | } 29 | } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/Galaxy.Libra.DapperExtensions/Predicate/PropertyPredicate.cs: -------------------------------------------------------------------------------- 1 | using Galaxy.Libra.DapperExtensions.Sql; 2 | using System.Collections.Generic; 3 | 4 | namespace Galaxy.Libra.DapperExtensions.Predicate 5 | { 6 | public interface IPropertyPredicate : IComparePredicate 7 | { 8 | string PropertyName2 { get; set; } 9 | } 10 | 11 | public class PropertyPredicate : ComparePredicate, IPropertyPredicate 12 | where T : class 13 | where T2 : class 14 | { 15 | public string PropertyName2 { get; set; } 16 | 17 | public override string GetSql(ISqlGenerator sqlGenerator, IDictionary parameters) 18 | { 19 | string columnName = GetColumnName(typeof(T), sqlGenerator, PropertyName); 20 | string columnName2 = GetColumnName(typeof(T2), sqlGenerator, PropertyName2); 21 | string operatorString = GetOperatorString(); 22 | return $"({columnName} {operatorString} {columnName2})"; 23 | } 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/Galaxy.Libra.DapperExtensions/DapperImpl/DapperImplementor.cs: -------------------------------------------------------------------------------- 1 | using Galaxy.Libra.DapperExtensions.Mapper; 2 | using Galaxy.Libra.DapperExtensions.Predicate; 3 | using Galaxy.Libra.DapperExtensions.PredicateConver; 4 | using Galaxy.Libra.DapperExtensions.Sql; 5 | 6 | namespace Galaxy.Libra.DapperExtensions.DapperImpl 7 | { 8 | public partial class DapperImplementor : IDapperImplementor 9 | { 10 | public DapperImplementor(ISqlGenerator sqlGenerator) 11 | { 12 | SqlGenerator = sqlGenerator; 13 | } 14 | 15 | public ISqlGenerator SqlGenerator { get; private set; } 16 | 17 | protected IPredicate GetPredicate(IClassMapper classMap, object predicate) 18 | { 19 | IPredicate wherePredicate = predicate as IPredicate; 20 | if (wherePredicate == null && predicate != null) 21 | { 22 | wherePredicate = EntityPredicateConvert.GetEntityPredicate(classMap, predicate); 23 | } 24 | 25 | return wherePredicate; 26 | } 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2019 Leeon 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /src/Galaxy.Libra.DapperExtensions.Test/DBBuilderTest.cs: -------------------------------------------------------------------------------- 1 | using Galaxy.Libra.DapperExtensions.DBBuilder.MySQL; 2 | using Galaxy.Libra.DapperExtensions.Sql; 3 | using Galaxy.Libra.DapperExtensions.Test.Entity; 4 | using MySql.Data.MySqlClient; 5 | using Xunit; 6 | 7 | namespace Galaxy.Libra.DapperExtensions.Test 8 | { 9 | public class DBBuilderTest 10 | { 11 | private string conStr = $"server=192.168.65.228;port=3307;user=root;password=123456;SslMode=None;"; 12 | private string conStr2 = $"server=192.168.65.228;port=3307;database=Test888;user=root;password=123456;SslMode=None;"; 13 | 14 | [Fact] 15 | public void Test() 16 | { 17 | Galaxy.Libra.DapperExtensions.DapperExtensions.SqlDialect = new MySqlDialect(); 18 | MySqlConnection conn = new MySqlConnection(conStr); 19 | MySQLDBBuilder mySQLDBBuilder = new MySQLDBBuilder(conn); 20 | mySQLDBBuilder.CreateDataBase("Test888"); 21 | 22 | MySqlConnection conn2 = new MySqlConnection(conStr2); 23 | MySQLTableBuilder mySQLTableBuilder = new MySQLTableBuilder(conn2); 24 | mySQLTableBuilder.CreateTable(typeof(TestEntity), new TestEntityMapper()); 25 | } 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/Galaxy.Libra.DapperExtensions/GetMultipleResult.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using Dapper; 6 | 7 | namespace Galaxy.Libra.DapperExtensions 8 | { 9 | public interface IMultipleResultReader 10 | { 11 | IEnumerable Read(); 12 | } 13 | 14 | public class GridReaderResultReader : IMultipleResultReader 15 | { 16 | private readonly SqlMapper.GridReader _reader; 17 | 18 | public GridReaderResultReader(SqlMapper.GridReader reader) 19 | { 20 | _reader = reader; 21 | } 22 | 23 | public IEnumerable Read() 24 | { 25 | return _reader.Read(); 26 | } 27 | } 28 | 29 | public class SequenceReaderResultReader : IMultipleResultReader 30 | { 31 | private readonly Queue _items; 32 | 33 | public SequenceReaderResultReader(IEnumerable items) 34 | { 35 | _items = new Queue(items); 36 | } 37 | 38 | public IEnumerable Read() 39 | { 40 | SqlMapper.GridReader reader = _items.Dequeue(); 41 | return reader.Read(); 42 | } 43 | } 44 | } -------------------------------------------------------------------------------- /src/Galaxy.Libra.DapperExtensions.Test/DapperExtensionsTest.cs: -------------------------------------------------------------------------------- 1 | using Galaxy.Libra.DapperExtensions.Sql; 2 | using Galaxy.Libra.DapperExtensions.Test.Entity; 3 | using MySql.Data.MySqlClient; 4 | using System.Data; 5 | using Xunit; 6 | 7 | namespace Galaxy.Libra.DapperExtensions.Test 8 | { 9 | public class DapperExtensionsTest 10 | { 11 | private string conStr = $"server=192.168.65.228;port=3307;database=Test123;user=root;password=123456;SslMode=None;"; 12 | 13 | [Fact] 14 | public void TestGet() 15 | { 16 | Galaxy.Libra.DapperExtensions.DapperExtensions.SqlDialect = new MySqlDialect(); 17 | 18 | using (MySqlConnection conn = new MySqlConnection(conStr)) 19 | { 20 | if (conn.State != ConnectionState.Open) 21 | conn.Open(); 22 | 23 | conn.Delete(u => u.Id == 1); 24 | User user = new User { Id = 1, Name = "123", Psw = "123", RoleId = "123" }; 25 | conn.Insert(user); 26 | var res = conn.GetList(u => u.Name == "123"); 27 | conn.Delete(user); 28 | conn.Close(); 29 | 30 | Assert.NotNull(res); 31 | } 32 | } 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/Galaxy.Libra.DapperExtensions/Sql/MySqlDialect.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | 5 | namespace Galaxy.Libra.DapperExtensions.Sql 6 | { 7 | public class MySqlDialect : SqlDialectBase 8 | { 9 | public override char OpenQuote 10 | { 11 | get { return '`'; } 12 | } 13 | 14 | public override char CloseQuote 15 | { 16 | get { return '`'; } 17 | } 18 | 19 | public override string GetIdentitySql(string tableName) 20 | { 21 | return "SELECT CONVERT(LAST_INSERT_ID(), SIGNED INTEGER) AS ID"; 22 | } 23 | 24 | public override string GetPagingSql(string sql, int page, int resultsPerPage, IDictionary parameters) 25 | { 26 | int startValue = page * resultsPerPage; 27 | return GetSetSql(sql, startValue, resultsPerPage, parameters); 28 | } 29 | 30 | public override string GetSetSql(string sql, int firstResult, int maxResults, IDictionary parameters) 31 | { 32 | string result = string.Format("{0} LIMIT @firstResult, @maxResults", sql); 33 | parameters.Add("@firstResult", firstResult); 34 | parameters.Add("@maxResults", maxResults); 35 | return result; 36 | } 37 | } 38 | } -------------------------------------------------------------------------------- /src/Galaxy.Libra.DapperExtensions.Test/SqlGeneratorUnitTest.cs: -------------------------------------------------------------------------------- 1 | using Galaxy.Libra.DapperExtensions.Mapper; 2 | using Galaxy.Libra.DapperExtensions.Predicate; 3 | using Galaxy.Libra.DapperExtensions.Sql; 4 | using Galaxy.Libra.DapperExtensions.Test.Entity; 5 | using System.Collections.Generic; 6 | using System.Reflection; 7 | using Xunit; 8 | 9 | namespace Galaxy.Libra.DapperExtensions.Test 10 | { 11 | public class SqlGeneratorUnitTest 12 | { 13 | [Fact] 14 | public void Test() 15 | { 16 | IDapperExtensionsConfiguration conf = new DapperExtensionsConfiguration(typeof(AutoClassMapper<>), new List(), new MySqlDialect()); 17 | SqlGeneratorImpl sqlGeneratorImpl = new SqlGeneratorImpl(conf); 18 | 19 | IFieldPredicate nameFieldPredicate = Predicates.Field(p => p.Name, Operator.Like, "不知道%"); 20 | List sortList = new List(); 21 | sortList.Add(Predicates.Sort(u => u.Id)); 22 | string selectPagedSql = sqlGeneratorImpl.SelectPaged(new UserMapper(), nameFieldPredicate, sortList, 20, 2, new Dictionary()); 23 | string res = "SELECT `User`.`Id`, `User`.`Name`, `User`.`Psw`, `User`.`RoleId` FROM `User` WHERE (`User`.`Name` LIKE @Name_0) ORDER BY `User`.`Id` ASC LIMIT @firstResult, @maxResults"; 24 | Assert.Equal(selectPagedSql, res); 25 | } 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/Galaxy.Libra.DapperExtensions/PredicateConver/EntityPredicateConvert.cs: -------------------------------------------------------------------------------- 1 | using Galaxy.Libra.DapperExtensions.Mapper; 2 | using Galaxy.Libra.DapperExtensions.Predicate; 3 | using System; 4 | using System.Collections.Generic; 5 | 6 | namespace Galaxy.Libra.DapperExtensions.PredicateConver 7 | { 8 | public class EntityPredicateConvert 9 | { 10 | public static IPredicate GetEntityPredicate(IClassMapper classMap, object entity) 11 | { 12 | Type predicateType = typeof(FieldPredicate<>).MakeGenericType(classMap.EntityType); 13 | IList predicates = new List(); 14 | foreach (var kvp in ReflectionHelper.GetObjectValues(entity)) 15 | { 16 | IFieldPredicate fieldPredicate = Activator.CreateInstance(predicateType) as IFieldPredicate; 17 | fieldPredicate.Not = false; 18 | fieldPredicate.Operator = Operator.Eq; 19 | fieldPredicate.PropertyName = kvp.Key; 20 | fieldPredicate.Value = kvp.Value; 21 | predicates.Add(fieldPredicate); 22 | } 23 | 24 | return predicates.Count == 1 25 | ? predicates[0] 26 | : new PredicateGroup 27 | { 28 | Operator = GroupOperator.And, 29 | Predicates = predicates 30 | }; 31 | } 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/Galaxy.Libra.DapperExtensions/Predicate/BasePredicate.cs: -------------------------------------------------------------------------------- 1 | using Galaxy.Libra.DapperExtensions.Mapper; 2 | using Galaxy.Libra.DapperExtensions.Sql; 3 | using System; 4 | using System.Collections.Generic; 5 | using System.Linq; 6 | 7 | namespace Galaxy.Libra.DapperExtensions.Predicate 8 | { 9 | public interface IPredicate 10 | { 11 | string GetSql(ISqlGenerator sqlGenerator, IDictionary parameters); 12 | } 13 | 14 | public interface IBasePredicate : IPredicate 15 | { 16 | string PropertyName { get; set; } 17 | } 18 | 19 | public abstract class BasePredicate : IBasePredicate 20 | { 21 | public abstract string GetSql(ISqlGenerator sqlGenerator, IDictionary parameters); 22 | public string PropertyName { get; set; } 23 | 24 | protected virtual string GetColumnName(Type entityType, ISqlGenerator sqlGenerator, string propertyName) 25 | { 26 | IClassMapper map = sqlGenerator.Configuration.GetMap(entityType); 27 | if (map == null) 28 | throw new NullReferenceException($"{entityType}找不到ClassMap映射文件"); 29 | 30 | IPropertyMap propertyMap = map.Properties.SingleOrDefault(p => p.Name == propertyName); 31 | if (propertyMap == null) 32 | throw new NullReferenceException($"{entityType}找不到属性{propertyName}"); 33 | 34 | return sqlGenerator.GetColumnName(map, propertyMap, false); 35 | } 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /src/Galaxy.Libra.DapperExtensions/Predicate/BetweenPredicate.cs: -------------------------------------------------------------------------------- 1 | using Galaxy.Libra.DapperExtensions.Sql; 2 | using System.Collections.Generic; 3 | 4 | namespace Galaxy.Libra.DapperExtensions.Predicate 5 | { 6 | public struct BetweenValues 7 | { 8 | public object Value1 { get; set; } 9 | public object Value2 { get; set; } 10 | } 11 | 12 | public interface IBetweenPredicate : IPredicate 13 | { 14 | string PropertyName { get; set; } 15 | BetweenValues Value { get; set; } 16 | bool Not { get; set; } 17 | } 18 | 19 | public class BetweenPredicate : BasePredicate, IBetweenPredicate 20 | where T : class 21 | { 22 | public override string GetSql(ISqlGenerator sqlGenerator, IDictionary parameters) 23 | { 24 | string columnName = GetColumnName(typeof(T), sqlGenerator, PropertyName); 25 | string notStr = Not ? "NOT " : string.Empty; 26 | string propertyName1 = parameters.SetParameterName(this.PropertyName, this.Value.Value1, sqlGenerator.Configuration.Dialect.ParameterPrefix); 27 | string propertyName2 = parameters.SetParameterName(this.PropertyName, this.Value.Value2, sqlGenerator.Configuration.Dialect.ParameterPrefix); 28 | return $"({columnName} {notStr}BETWEEN {propertyName1} AND {propertyName2})"; 29 | } 30 | 31 | public BetweenValues Value { get; set; } 32 | 33 | public bool Not { get; set; } 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/Galaxy.Libra.DapperExtensions/Predicate/ExistsPredicate.cs: -------------------------------------------------------------------------------- 1 | using Galaxy.Libra.DapperExtensions.Mapper; 2 | using Galaxy.Libra.DapperExtensions.Sql; 3 | using System; 4 | using System.Collections.Generic; 5 | 6 | namespace Galaxy.Libra.DapperExtensions.Predicate 7 | { 8 | public interface IExistsPredicate : IPredicate 9 | { 10 | IPredicate Predicate { get; set; } 11 | bool Not { get; set; } 12 | } 13 | 14 | public class ExistsPredicate : IExistsPredicate 15 | where TSub : class 16 | { 17 | public IPredicate Predicate { get; set; } 18 | public bool Not { get; set; } 19 | 20 | public string GetSql(ISqlGenerator sqlGenerator, IDictionary parameters) 21 | { 22 | IClassMapper mapSub = GetClassMapper(typeof(TSub), sqlGenerator.Configuration); 23 | string notStr = Not ? "NOT " : string.Empty; 24 | string tableName = sqlGenerator.GetTableName(mapSub); 25 | string predicateSql = Predicate.GetSql(sqlGenerator, parameters); 26 | return $"({notStr}EXISTS (SELECT 1 FROM {tableName} WHERE {predicateSql}))"; 27 | } 28 | 29 | protected virtual IClassMapper GetClassMapper(Type type, IDapperExtensionsConfiguration configuration) 30 | { 31 | IClassMapper map = configuration.GetMap(type); 32 | 33 | if (map == null) 34 | throw new NullReferenceException($"{type}找不到ClassMap映射文件"); 35 | 36 | return map; 37 | } 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /src/Galaxy.Libra.DapperExtensions.Test/TestEntityRepositoryTest.cs: -------------------------------------------------------------------------------- 1 | using Galaxy.Libra.DapperExtensions.EntityRepository; 2 | using Galaxy.Libra.DapperExtensions.Sql; 3 | using Galaxy.Libra.DapperExtensions.Test.Entity; 4 | using MySql.Data.MySqlClient; 5 | using System; 6 | using System.Collections.Generic; 7 | using System.Linq; 8 | using System.Text; 9 | using Xunit; 10 | 11 | namespace Galaxy.Libra.DapperExtensions.Test 12 | { 13 | public class UserRepositoryTest 14 | { 15 | [Fact] 16 | public void Test() 17 | { 18 | TestEntityRepository testEntityRepository = new TestEntityRepository(); 19 | 20 | TestEntity t = new TestEntity 21 | { 22 | Name = "test", 23 | TestInt = 1 24 | }; 25 | 26 | testEntityRepository.Add(t); 27 | TestEntity t2 = testEntityRepository.GetList(u => u.Name == "test")?.FirstOrDefault(); 28 | testEntityRepository.Delete(t3 => t3.Id == t2.Id); 29 | testEntityRepository.Delete(t3 => t3.Name == t2.Name); 30 | } 31 | } 32 | 33 | public class TestEntityRepository : BaseEntityRepository 34 | { 35 | private string conStr = $"server=192.168.65.228;port=3307;database=Test888;user=root;password=123456;SslMode=None;"; 36 | 37 | public TestEntityRepository() 38 | { 39 | Galaxy.Libra.DapperExtensions.DapperExtensions.SqlDialect = new MySqlDialect(); 40 | curDbConnection = new MySqlConnection(conStr); 41 | } 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /src/Galaxy.Libra.DapperExtensions/Sql/PostgreSqlDialect.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | 6 | namespace Galaxy.Libra.DapperExtensions.Sql 7 | { 8 | public class PostgreSqlDialect : SqlDialectBase 9 | { 10 | public override string GetIdentitySql(string tableName) 11 | { 12 | return "SELECT LASTVAL() AS Id"; 13 | } 14 | 15 | public override string GetPagingSql(string sql, int page, int resultsPerPage, IDictionary parameters) 16 | { 17 | int startValue = page * resultsPerPage; 18 | return GetSetSql(sql, startValue, resultsPerPage, parameters); 19 | } 20 | 21 | public override string GetSetSql(string sql, int firstResult, int maxResults, IDictionary parameters) 22 | { 23 | string result = string.Format("{0} LIMIT @firstResult OFFSET @pageStartRowNbr", sql); 24 | parameters.Add("@firstResult", firstResult); 25 | parameters.Add("@maxResults", maxResults); 26 | return result; 27 | } 28 | 29 | public override string GetColumnName(string prefix, string columnName, string alias) 30 | { 31 | return base.GetColumnName(null, columnName, alias).ToLower(); 32 | } 33 | 34 | public override string GetTableName(string schemaName, string tableName, string alias) 35 | { 36 | return base.GetTableName(schemaName, tableName, alias).ToLower(); 37 | } 38 | } 39 | 40 | } -------------------------------------------------------------------------------- /src/Galaxy.Libra.DapperExtensions/GetMultiplePredicate.cs: -------------------------------------------------------------------------------- 1 | using Galaxy.Libra.DapperExtensions.Predicate; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.Linq; 5 | using System.Text; 6 | 7 | namespace Galaxy.Libra.DapperExtensions 8 | { 9 | public class GetMultiplePredicate 10 | { 11 | private readonly List _items; 12 | 13 | public GetMultiplePredicate() 14 | { 15 | _items = new List(); 16 | } 17 | 18 | public IEnumerable Items 19 | { 20 | get { return _items.AsReadOnly(); } 21 | } 22 | 23 | public void Add(IPredicate predicate, IList sort = null) where T : class 24 | { 25 | _items.Add(new GetMultiplePredicateItem 26 | { 27 | Value = predicate, 28 | Type = typeof(T), 29 | Sort = sort 30 | }); 31 | } 32 | 33 | public void Add(object id) where T : class 34 | { 35 | _items.Add(new GetMultiplePredicateItem 36 | { 37 | Value = id, 38 | Type = typeof (T) 39 | }); 40 | } 41 | 42 | public class GetMultiplePredicateItem 43 | { 44 | public object Value { get; set; } 45 | public Type Type { get; set; } 46 | public IList Sort { get; set; } 47 | } 48 | } 49 | } -------------------------------------------------------------------------------- /src/Galaxy.Libra.DapperExtensions/Predicate/PredicateGroup.cs: -------------------------------------------------------------------------------- 1 | using Galaxy.Libra.DapperExtensions.Sql; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | 6 | namespace Galaxy.Libra.DapperExtensions.Predicate 7 | { 8 | public interface IPredicateGroup : IPredicate 9 | { 10 | GroupOperator Operator { get; set; } 11 | IList Predicates { get; set; } 12 | } 13 | 14 | /// 15 | /// Groups IPredicates together using the specified group operator. 16 | /// 17 | public class PredicateGroup : IPredicateGroup 18 | { 19 | public GroupOperator Operator { get; set; } 20 | public IList Predicates { get; set; } 21 | public string GetSql(ISqlGenerator sqlGenerator, IDictionary parameters) 22 | { 23 | string seperator = Operator == GroupOperator.And ? " AND " : " OR "; 24 | return "(" + Predicates.Aggregate(new StringBuilder(), 25 | (sb, p) => (sb.Length == 0 ? sb : sb.Append(seperator)).Append(p.GetSql(sqlGenerator, parameters)), 26 | sb => 27 | { 28 | var s = sb.ToString(); 29 | if (s.Length == 0) return sqlGenerator.Configuration.Dialect.EmptyExpression; 30 | return s; 31 | } 32 | ) + ")"; 33 | } 34 | } 35 | 36 | /// 37 | /// Operator to use when joining predicates in a PredicateGroup. 38 | /// 39 | public enum GroupOperator 40 | { 41 | And, 42 | Or 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /src/Galaxy.Libra.DapperExtensions/PredicateConver/KeyPredicateConvert.cs: -------------------------------------------------------------------------------- 1 | using Galaxy.Libra.DapperExtensions.Mapper; 2 | using Galaxy.Libra.DapperExtensions.Predicate; 3 | using System; 4 | using System.Collections.Generic; 5 | using System.Linq; 6 | 7 | namespace Galaxy.Libra.DapperExtensions.PredicateConver 8 | { 9 | public class KeyPredicateConvert 10 | { 11 | public static IPredicate GetKeyPredicate(IClassMapper classMap, T entity) where T : class 12 | { 13 | var whereFields = classMap.Properties.Where(p => p.KeyType != KeyType.NotAKey); 14 | if (!whereFields.Any()) 15 | { 16 | throw new ArgumentException("At least one Key column must be defined."); 17 | } 18 | 19 | IList predicates = (from field in whereFields 20 | select new FieldPredicate 21 | { 22 | Not = false, 23 | Operator = Operator.Eq, 24 | PropertyName = field.Name, 25 | Value = field.PropertyInfo.GetValue(entity, null) 26 | }).Cast().ToList(); 27 | 28 | return predicates.Count == 1 29 | ? predicates[0] 30 | : new PredicateGroup 31 | { 32 | Operator = GroupOperator.And, 33 | Predicates = predicates 34 | }; 35 | } 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /src/Galaxy.Libra.DapperExtensions/DapperImpl/DapperImplementorUpdate.cs: -------------------------------------------------------------------------------- 1 | using Dapper; 2 | using Galaxy.Libra.DapperExtensions.Mapper; 3 | using Galaxy.Libra.DapperExtensions.Predicate; 4 | using Galaxy.Libra.DapperExtensions.PredicateConver; 5 | using System.Collections.Generic; 6 | using System.Data; 7 | using System.Linq; 8 | 9 | namespace Galaxy.Libra.DapperExtensions.DapperImpl 10 | { 11 | public partial class DapperImplementor 12 | { 13 | public bool Update(IDbConnection connection, T entity, IDbTransaction transaction, int? commandTimeout) where T : class 14 | { 15 | IClassMapper classMap = SqlGenerator.Configuration.GetMap(); 16 | IPredicate predicate = KeyPredicateConvert.GetKeyPredicate(classMap, entity); 17 | Dictionary parameters = new Dictionary(); 18 | string sql = SqlGenerator.Update(classMap, predicate, parameters); 19 | DynamicParameters dynamicParameters = new DynamicParameters(); 20 | 21 | var columns = classMap.Properties.Where(p => !(p.Ignored || p.IsReadOnly || p.KeyType == KeyType.Identity)); 22 | foreach (var property in ReflectionHelper.GetObjectValues(entity).Where(property => columns.Any(c => c.Name == property.Key))) 23 | { 24 | dynamicParameters.Add(property.Key, property.Value); 25 | } 26 | 27 | foreach (var parameter in parameters) 28 | { 29 | dynamicParameters.Add(parameter.Key, parameter.Value); 30 | } 31 | 32 | return connection.Execute(sql, dynamicParameters, transaction, commandTimeout, CommandType.Text) > 0; 33 | } 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/Galaxy.Libra.DapperExtensions.sln: -------------------------------------------------------------------------------- 1 | 2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio 15 4 | VisualStudioVersion = 15.0.27004.2009 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Galaxy.Libra.DapperExtensions", "Galaxy.Libra.DapperExtensions\Galaxy.Libra.DapperExtensions.csproj", "{A496BE25-6B6A-42B6-906B-A1858222EEF2}" 7 | EndProject 8 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Galaxy.Libra.DapperExtensions.Test", "Galaxy.Libra.DapperExtensions.Test\Galaxy.Libra.DapperExtensions.Test.csproj", "{E86EE299-349C-47BF-84AF-4EABA82A7DE5}" 9 | EndProject 10 | Global 11 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 12 | Debug|Any CPU = Debug|Any CPU 13 | Release|Any CPU = Release|Any CPU 14 | EndGlobalSection 15 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 16 | {A496BE25-6B6A-42B6-906B-A1858222EEF2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 17 | {A496BE25-6B6A-42B6-906B-A1858222EEF2}.Debug|Any CPU.Build.0 = Debug|Any CPU 18 | {A496BE25-6B6A-42B6-906B-A1858222EEF2}.Release|Any CPU.ActiveCfg = Release|Any CPU 19 | {A496BE25-6B6A-42B6-906B-A1858222EEF2}.Release|Any CPU.Build.0 = Release|Any CPU 20 | {E86EE299-349C-47BF-84AF-4EABA82A7DE5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 21 | {E86EE299-349C-47BF-84AF-4EABA82A7DE5}.Debug|Any CPU.Build.0 = Debug|Any CPU 22 | {E86EE299-349C-47BF-84AF-4EABA82A7DE5}.Release|Any CPU.ActiveCfg = Release|Any CPU 23 | {E86EE299-349C-47BF-84AF-4EABA82A7DE5}.Release|Any CPU.Build.0 = Release|Any CPU 24 | EndGlobalSection 25 | GlobalSection(SolutionProperties) = preSolution 26 | HideSolutionNode = FALSE 27 | EndGlobalSection 28 | GlobalSection(ExtensibilityGlobals) = postSolution 29 | SolutionGuid = {5E880D38-CD31-40C7-BCE3-118A46552FFB} 30 | EndGlobalSection 31 | EndGlobal 32 | -------------------------------------------------------------------------------- /src/Galaxy.Libra.DapperExtensions/EntityRepository/IBaseEntityRepository.cs: -------------------------------------------------------------------------------- 1 | using Galaxy.Libra.DapperExtensions.Predicate; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.Linq.Expressions; 5 | 6 | namespace Galaxy.Libra.DapperExtensions.EntityRepository 7 | { 8 | public interface IBaseEntityRepository where T : class 9 | { 10 | #region 增删改 11 | 12 | dynamic Add(T entity); 13 | 14 | bool Update(T entity); 15 | 16 | bool Delete(Expression> expression); 17 | 18 | #endregion 19 | 20 | /// 21 | /// 获得,全部参数为null 22 | /// 23 | /// 参数示例,如:new { LastName = "Bar", FirstName = "Foo" }, 更多的请使用Predicates 24 | /// 25 | List GetList(object predicate = null); 26 | 27 | List GetList(Expression> expression); 28 | 29 | /// 30 | /// 获取分页数据 31 | /// 32 | /// 页索引 33 | /// 每页记录数 34 | /// 是否缓存 35 | /// 参数示例,如:new { LastName = "Bar", FirstName = "Foo" }, 更多的请使用Predicates 36 | /// 37 | List GetPage(int page, int resultsPerPage, IList sort, object predicate = null); 38 | 39 | List GetPage(int page, int resultsPerPage, IList sort, Expression> expression); 40 | 41 | /// 42 | /// 数量 43 | /// 44 | /// 参数示例,如:new { LastName = "Bar", FirstName = "Foo" }, 更多的请使用Predicates 45 | /// 46 | int Count(object predicate = null); 47 | 48 | int Count(Expression> expression); 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /src/Galaxy.Libra.DapperExtensions/PredicateConver/IdPredicateConvert.cs: -------------------------------------------------------------------------------- 1 | using Galaxy.Libra.DapperExtensions.Mapper; 2 | using Galaxy.Libra.DapperExtensions.Predicate; 3 | using System; 4 | using System.Collections.Generic; 5 | using System.Linq; 6 | 7 | namespace Galaxy.Libra.DapperExtensions.PredicateConver 8 | { 9 | public class IdPredicateConvert 10 | { 11 | public static IPredicate GetIdPredicate(IClassMapper classMap, object id) 12 | { 13 | bool isSimpleType = ReflectionHelper.IsSimpleType(id.GetType()); 14 | var keys = classMap.Properties.Where(p => p.KeyType != KeyType.NotAKey); 15 | IDictionary paramValues = null; 16 | IList predicates = new List(); 17 | if (!isSimpleType) 18 | { 19 | paramValues = ReflectionHelper.GetObjectValues(id); 20 | } 21 | 22 | foreach (var key in keys) 23 | { 24 | object value = id; 25 | if (!isSimpleType) 26 | { 27 | value = paramValues[key.Name]; 28 | } 29 | 30 | Type predicateType = typeof(FieldPredicate<>).MakeGenericType(classMap.EntityType); 31 | 32 | IFieldPredicate fieldPredicate = Activator.CreateInstance(predicateType) as IFieldPredicate; 33 | fieldPredicate.Not = false; 34 | fieldPredicate.Operator = Operator.Eq; 35 | fieldPredicate.PropertyName = key.Name; 36 | fieldPredicate.Value = value; 37 | predicates.Add(fieldPredicate); 38 | } 39 | 40 | return predicates.Count == 1 41 | ? predicates[0] 42 | : new PredicateGroup 43 | { 44 | Operator = GroupOperator.And, 45 | Predicates = predicates 46 | }; 47 | } 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /src/Galaxy.Libra.DapperExtensions/Sql/SqliteDialect.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | 5 | namespace Galaxy.Libra.DapperExtensions.Sql 6 | { 7 | public class SqliteDialect : SqlDialectBase 8 | { 9 | public override string GetIdentitySql(string tableName) 10 | { 11 | return "SELECT LAST_INSERT_ROWID() AS [Id]"; 12 | } 13 | 14 | public override string GetPagingSql(string sql, int page, int resultsPerPage, IDictionary parameters) 15 | { 16 | int startValue = page * resultsPerPage; 17 | return GetSetSql(sql, startValue, resultsPerPage, parameters); 18 | } 19 | 20 | public override string GetSetSql(string sql, int firstResult, int maxResults, IDictionary parameters) 21 | { 22 | if (string.IsNullOrEmpty(sql)) 23 | { 24 | throw new ArgumentNullException("SQL"); 25 | } 26 | 27 | if (parameters == null) 28 | { 29 | throw new ArgumentNullException("Parameters"); 30 | } 31 | 32 | var result = string.Format("{0} LIMIT @Offset, @Count", sql); 33 | parameters.Add("@Offset", firstResult); 34 | parameters.Add("@Count", maxResults); 35 | return result; 36 | } 37 | 38 | public override string GetColumnName(string prefix, string columnName, string alias) 39 | { 40 | if (string.IsNullOrWhiteSpace(columnName)) 41 | { 42 | throw new ArgumentNullException(columnName, "columnName cannot be null or empty."); 43 | } 44 | var result = new StringBuilder(); 45 | result.AppendFormat(columnName); 46 | if (!string.IsNullOrWhiteSpace(alias)) 47 | { 48 | result.AppendFormat(" AS {0}", QuoteString(alias)); 49 | } 50 | return result.ToString(); 51 | } 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /src/Galaxy.Libra.DapperExtensions/Predicate/FieldPredicate.cs: -------------------------------------------------------------------------------- 1 | using Galaxy.Libra.DapperExtensions.Sql; 2 | using System; 3 | using System.Collections; 4 | using System.Collections.Generic; 5 | using System.Linq; 6 | using System.Text; 7 | 8 | namespace Galaxy.Libra.DapperExtensions.Predicate 9 | { 10 | public interface IFieldPredicate : IComparePredicate 11 | { 12 | object Value { get; set; } 13 | } 14 | 15 | public class FieldPredicate : ComparePredicate, IFieldPredicate 16 | where T : class 17 | { 18 | public object Value { get; set; } 19 | 20 | public override string GetSql(ISqlGenerator sqlGenerator, IDictionary parameters) 21 | { 22 | string columnName = GetColumnName(typeof(T), sqlGenerator, PropertyName); 23 | if (Value == null) 24 | return $"({columnName} IS {NotStr}NULL)"; 25 | 26 | if (Value is IEnumerable && !(Value is string)) 27 | { 28 | if (Operator != Operator.Eq) 29 | throw new ArgumentException("Operator must be set to Eq for Enumerable types"); 30 | 31 | List @params = new List(); 32 | foreach (var value in (IEnumerable)Value) 33 | { 34 | string valueParameterName = parameters.SetParameterName(this.PropertyName, value, sqlGenerator.Configuration.Dialect.ParameterPrefix); 35 | @params.Add(valueParameterName); 36 | } 37 | 38 | string paramStrings = @params.Aggregate(new StringBuilder(), (sb, s) => sb.Append((sb.Length != 0 ? ", " : string.Empty) + s), sb => sb.ToString()); 39 | return $"({columnName} {NotStr}IN ({paramStrings}))"; 40 | } 41 | 42 | string parameterName = parameters.SetParameterName(this.PropertyName, this.Value, sqlGenerator.Configuration.Dialect.ParameterPrefix); 43 | string operatorString = GetOperatorString(); 44 | return $"({columnName} {operatorString} {parameterName})"; 45 | } 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /src/Galaxy.Libra.DapperExtensions/Predicate/ComparePredicate.cs: -------------------------------------------------------------------------------- 1 | namespace Galaxy.Libra.DapperExtensions.Predicate 2 | { 3 | public interface IComparePredicate : IBasePredicate 4 | { 5 | Operator Operator { get; set; } 6 | bool Not { get; set; } 7 | } 8 | 9 | public abstract class ComparePredicate : BasePredicate 10 | { 11 | public Operator Operator { get; set; } 12 | public bool Not { get; set; } 13 | public string NotStr 14 | { 15 | get 16 | { 17 | return Not ? "NOT " : string.Empty; 18 | } 19 | } 20 | 21 | public virtual string GetOperatorString() 22 | { 23 | switch (Operator) 24 | { 25 | case Operator.Gt: 26 | return Not ? "<=" : ">"; 27 | case Operator.Ge: 28 | return Not ? "<" : ">="; 29 | case Operator.Lt: 30 | return Not ? ">=" : "<"; 31 | case Operator.Le: 32 | return Not ? ">" : "<="; 33 | case Operator.Like: 34 | return Not ? "NOT LIKE" : "LIKE"; 35 | default: 36 | return Not ? "<>" : "="; 37 | } 38 | } 39 | } 40 | 41 | /// 42 | /// 操作符。 43 | /// 44 | public enum Operator 45 | { 46 | /// 47 | /// Equal to 48 | /// 49 | Eq, 50 | 51 | /// 52 | /// Greater than 53 | /// 54 | Gt, 55 | 56 | /// 57 | /// Greater than or equal to 58 | /// 59 | Ge, 60 | 61 | /// 62 | /// Less than 63 | /// 64 | Lt, 65 | 66 | /// 67 | /// Less than or equal to 68 | /// 69 | Le, 70 | 71 | /// 72 | /// Like (You can use % in the value to do wilcard searching) 73 | /// 74 | Like 75 | } 76 | } 77 | -------------------------------------------------------------------------------- /src/Galaxy.Libra.DapperExtensions/DapperImpl/DapperImplementorCount.cs: -------------------------------------------------------------------------------- 1 | using Dapper; 2 | using Galaxy.Libra.DapperExtensions.Mapper; 3 | using Galaxy.Libra.DapperExtensions.Predicate; 4 | using Galaxy.Libra.DapperExtensions.PredicateConver; 5 | using System; 6 | using System.Collections.Generic; 7 | using System.Data; 8 | using System.Linq; 9 | using System.Linq.Expressions; 10 | 11 | namespace Galaxy.Libra.DapperExtensions.DapperImpl 12 | { 13 | public partial class DapperImplementor 14 | { 15 | public int Count(IDbConnection connection, object predicate, IDbTransaction transaction, int? commandTimeout) where T : class 16 | { 17 | IClassMapper classMap = SqlGenerator.Configuration.GetMap(); 18 | IPredicate wherePredicate = GetPredicate(classMap, predicate); 19 | return Count(connection, classMap, wherePredicate, transaction, commandTimeout); 20 | } 21 | 22 | public int Count(IDbConnection connection, Expression> expression, IDbTransaction transaction, int? commandTimeout) where T : class 23 | { 24 | IClassMapper classMap = SqlGenerator.Configuration.GetMap(); 25 | IPredicate wherePredicate = ExpressionPredicateConvert.GetExpressionPredicate(expression); 26 | return Count(connection, classMap, wherePredicate, transaction, commandTimeout); 27 | } 28 | 29 | protected int Count(IDbConnection connection, IClassMapper classMap, IPredicate predicate, IDbTransaction transaction, int? commandTimeout) where T : class 30 | { 31 | Dictionary parameters = new Dictionary(); 32 | string sql = SqlGenerator.Count(classMap, predicate, parameters); 33 | DynamicParameters dynamicParameters = new DynamicParameters(); 34 | foreach (var parameter in parameters) 35 | { 36 | dynamicParameters.Add(parameter.Key, parameter.Value); 37 | } 38 | 39 | return (int)connection.Query(sql, dynamicParameters, transaction, false, commandTimeout, CommandType.Text).Single().Total; 40 | } 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /src/Galaxy.Libra.DapperExtensions/DapperImpl/DapperImplementorGetList.cs: -------------------------------------------------------------------------------- 1 | using Dapper; 2 | using Galaxy.Libra.DapperExtensions.Mapper; 3 | using Galaxy.Libra.DapperExtensions.Predicate; 4 | using Galaxy.Libra.DapperExtensions.PredicateConver; 5 | using System; 6 | using System.Collections.Generic; 7 | using System.Data; 8 | using System.Linq.Expressions; 9 | 10 | namespace Galaxy.Libra.DapperExtensions.DapperImpl 11 | { 12 | public partial class DapperImplementor 13 | { 14 | public IEnumerable GetList(IDbConnection connection, object predicate, IList sort, IDbTransaction transaction, int? commandTimeout, bool buffered) where T : class 15 | { 16 | IClassMapper classMap = SqlGenerator.Configuration.GetMap(); 17 | IPredicate wherePredicate = GetPredicate(classMap, predicate); 18 | return GetList(connection, classMap, wherePredicate, sort, transaction, commandTimeout, true); 19 | } 20 | 21 | public IEnumerable GetList(IDbConnection connection, Expression> expression, IList sort, IDbTransaction transaction, int? commandTimeout, bool buffered) where T : class 22 | { 23 | IClassMapper classMap = SqlGenerator.Configuration.GetMap(); 24 | IPredicate wherePredicate = ExpressionPredicateConvert.GetExpressionPredicate(expression); 25 | return GetList(connection, classMap, wherePredicate, sort, transaction, commandTimeout, true); 26 | } 27 | 28 | protected IEnumerable GetList(IDbConnection connection, IClassMapper classMap, IPredicate predicate, IList sort, IDbTransaction transaction, int? commandTimeout, bool buffered) where T : class 29 | { 30 | Dictionary parameters = new Dictionary(); 31 | string sql = SqlGenerator.Select(classMap, predicate, sort, parameters); 32 | DynamicParameters dynamicParameters = new DynamicParameters(); 33 | foreach (var parameter in parameters) 34 | { 35 | dynamicParameters.Add(parameter.Key, parameter.Value); 36 | } 37 | 38 | return connection.Query(sql, dynamicParameters, transaction, buffered, commandTimeout, CommandType.Text); 39 | } 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /src/Galaxy.Libra.DapperExtensions/Sql/SqlCeDialect.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | 6 | namespace Galaxy.Libra.DapperExtensions.Sql 7 | { 8 | public class SqlCeDialect : SqlDialectBase 9 | { 10 | public override char OpenQuote 11 | { 12 | get { return '['; } 13 | } 14 | 15 | public override char CloseQuote 16 | { 17 | get { return ']'; } 18 | } 19 | 20 | public override bool SupportsMultipleStatements 21 | { 22 | get { return false; } 23 | } 24 | 25 | public override string GetTableName(string schemaName, string tableName, string alias) 26 | { 27 | if (string.IsNullOrWhiteSpace(tableName)) 28 | { 29 | throw new ArgumentNullException("TableName"); 30 | } 31 | 32 | StringBuilder result = new StringBuilder(); 33 | result.Append(OpenQuote); 34 | if (!string.IsNullOrWhiteSpace(schemaName)) 35 | { 36 | result.AppendFormat("{0}_", schemaName); 37 | } 38 | 39 | result.AppendFormat("{0}{1}", tableName, CloseQuote); 40 | 41 | 42 | if (!string.IsNullOrWhiteSpace(alias)) 43 | { 44 | result.AppendFormat(" AS {0}{1}{2}", OpenQuote, alias, CloseQuote); 45 | } 46 | 47 | return result.ToString(); 48 | } 49 | 50 | public override string GetIdentitySql(string tableName) 51 | { 52 | return "SELECT CAST(@@IDENTITY AS BIGINT) AS [Id]"; 53 | } 54 | 55 | public override string GetPagingSql(string sql, int page, int resultsPerPage, IDictionary parameters) 56 | { 57 | int startValue = (page * resultsPerPage); 58 | return GetSetSql(sql, startValue, resultsPerPage, parameters); 59 | } 60 | 61 | public override string GetSetSql(string sql, int firstResult, int maxResults, IDictionary parameters) 62 | { 63 | string result = string.Format("{0} OFFSET @firstResult ROWS FETCH NEXT @maxResults ROWS ONLY", sql); 64 | parameters.Add("@firstResult", firstResult); 65 | parameters.Add("@maxResults", maxResults); 66 | return result; 67 | } 68 | } 69 | } -------------------------------------------------------------------------------- /src/Galaxy.Libra.DapperExtensions/DapperImpl/DapperImplementorGetPage.cs: -------------------------------------------------------------------------------- 1 | using Dapper; 2 | using Galaxy.Libra.DapperExtensions.Mapper; 3 | using Galaxy.Libra.DapperExtensions.Predicate; 4 | using Galaxy.Libra.DapperExtensions.PredicateConver; 5 | using System; 6 | using System.Collections.Generic; 7 | using System.Data; 8 | using System.Linq.Expressions; 9 | 10 | namespace Galaxy.Libra.DapperExtensions.DapperImpl 11 | { 12 | public partial class DapperImplementor 13 | { 14 | public IEnumerable GetPage(IDbConnection connection, object predicate, IList sort, int page, int resultsPerPage, IDbTransaction transaction, int? commandTimeout, bool buffered) where T : class 15 | { 16 | IClassMapper classMap = SqlGenerator.Configuration.GetMap(); 17 | IPredicate wherePredicate = GetPredicate(classMap, predicate); 18 | return GetPage(connection, classMap, wherePredicate, sort, page, resultsPerPage, transaction, commandTimeout, buffered); 19 | } 20 | 21 | public IEnumerable GetPage(IDbConnection connection, Expression> expression, IList sort, int page, int resultsPerPage, IDbTransaction transaction, int? commandTimeout, bool buffered) where T : class 22 | { 23 | IClassMapper classMap = SqlGenerator.Configuration.GetMap(); 24 | IPredicate wherePredicate = ExpressionPredicateConvert.GetExpressionPredicate(expression); 25 | return GetPage(connection, classMap, wherePredicate, sort, page, resultsPerPage, transaction, commandTimeout, buffered); 26 | } 27 | 28 | protected IEnumerable GetPage(IDbConnection connection, IClassMapper classMap, IPredicate predicate, IList sort, int page, int resultsPerPage, IDbTransaction transaction, int? commandTimeout, bool buffered) where T : class 29 | { 30 | Dictionary parameters = new Dictionary(); 31 | string sql = SqlGenerator.SelectPaged(classMap, predicate, sort, page, resultsPerPage, parameters); 32 | DynamicParameters dynamicParameters = new DynamicParameters(); 33 | foreach (var parameter in parameters) 34 | { 35 | dynamicParameters.Add(parameter.Key, parameter.Value); 36 | } 37 | 38 | return connection.Query(sql, dynamicParameters, transaction, buffered, commandTimeout, CommandType.Text); 39 | } 40 | 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /src/Galaxy.Libra.DapperExtensions/DapperImpl/DapperImplementorGetSet.cs: -------------------------------------------------------------------------------- 1 | using Dapper; 2 | using Galaxy.Libra.DapperExtensions.Mapper; 3 | using Galaxy.Libra.DapperExtensions.Predicate; 4 | using Galaxy.Libra.DapperExtensions.PredicateConver; 5 | using System; 6 | using System.Collections.Generic; 7 | using System.Data; 8 | using System.Linq.Expressions; 9 | 10 | namespace Galaxy.Libra.DapperExtensions.DapperImpl 11 | { 12 | public partial class DapperImplementor 13 | { 14 | public IEnumerable GetSet(IDbConnection connection, object predicate, IList sort, int firstResult, int maxResults, IDbTransaction transaction, int? commandTimeout, bool buffered) where T : class 15 | { 16 | IClassMapper classMap = SqlGenerator.Configuration.GetMap(); 17 | IPredicate wherePredicate = GetPredicate(classMap, predicate); 18 | return GetSet(connection, classMap, wherePredicate, sort, firstResult, maxResults, transaction, commandTimeout, buffered); 19 | } 20 | 21 | public IEnumerable GetSet(IDbConnection connection, Expression> expression, IList sort, int firstResult, int maxResults, IDbTransaction transaction, int? commandTimeout, bool buffered) where T : class 22 | { 23 | IClassMapper classMap = SqlGenerator.Configuration.GetMap(); 24 | IPredicate wherePredicate = ExpressionPredicateConvert.GetExpressionPredicate(expression); 25 | return GetSet(connection, classMap, wherePredicate, sort, firstResult, maxResults, transaction, commandTimeout, buffered); 26 | } 27 | 28 | protected IEnumerable GetSet(IDbConnection connection, IClassMapper classMap, IPredicate predicate, IList sort, int firstResult, int maxResults, IDbTransaction transaction, int? commandTimeout, bool buffered) where T : class 29 | { 30 | Dictionary parameters = new Dictionary(); 31 | string sql = SqlGenerator.SelectSet(classMap, predicate, sort, firstResult, maxResults, parameters); 32 | DynamicParameters dynamicParameters = new DynamicParameters(); 33 | foreach (var parameter in parameters) 34 | { 35 | dynamicParameters.Add(parameter.Key, parameter.Value); 36 | } 37 | 38 | return connection.Query(sql, dynamicParameters, transaction, buffered, commandTimeout, CommandType.Text); 39 | } 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /src/Galaxy.Libra.DapperExtensions/DapperImpl/DapperImplementorDelete.cs: -------------------------------------------------------------------------------- 1 | using Dapper; 2 | using Galaxy.Libra.DapperExtensions.Mapper; 3 | using Galaxy.Libra.DapperExtensions.Predicate; 4 | using Galaxy.Libra.DapperExtensions.PredicateConver; 5 | using System; 6 | using System.Collections.Generic; 7 | using System.Data; 8 | using System.Linq.Expressions; 9 | 10 | namespace Galaxy.Libra.DapperExtensions.DapperImpl 11 | { 12 | public partial class DapperImplementor 13 | { 14 | public bool Delete(IDbConnection connection, T entity, IDbTransaction transaction, int? commandTimeout) where T : class 15 | { 16 | IClassMapper classMap = SqlGenerator.Configuration.GetMap(); 17 | IPredicate predicate = KeyPredicateConvert.GetKeyPredicate(classMap, entity); 18 | return Delete(connection, classMap, predicate, transaction, commandTimeout); 19 | } 20 | 21 | public bool Delete(IDbConnection connection, object predicate, IDbTransaction transaction, int? commandTimeout) where T : class 22 | { 23 | IClassMapper classMap = SqlGenerator.Configuration.GetMap(); 24 | IPredicate wherePredicate = GetPredicate(classMap, predicate); 25 | return Delete(connection, classMap, wherePredicate, transaction, commandTimeout); 26 | } 27 | 28 | public bool Delete(IDbConnection connection, Expression> expression, IDbTransaction transaction, int? commandTimeout) where T : class 29 | { 30 | IClassMapper classMap = SqlGenerator.Configuration.GetMap(); 31 | IPredicate wherePredicate = ExpressionPredicateConvert.GetExpressionPredicate(expression); 32 | return Delete(connection, classMap, wherePredicate, transaction, commandTimeout); 33 | } 34 | 35 | protected bool Delete(IDbConnection connection, IClassMapper classMap, IPredicate predicate, IDbTransaction transaction, int? commandTimeout) where T : class 36 | { 37 | Dictionary parameters = new Dictionary(); 38 | string sql = SqlGenerator.Delete(classMap, predicate, parameters); 39 | DynamicParameters dynamicParameters = new DynamicParameters(); 40 | foreach (var parameter in parameters) 41 | { 42 | dynamicParameters.Add(parameter.Key, parameter.Value); 43 | } 44 | 45 | return connection.Execute(sql, dynamicParameters, transaction, commandTimeout, CommandType.Text) > 0; 46 | } 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | ############################################################################### 2 | # Set default behavior to automatically normalize line endings. 3 | ############################################################################### 4 | * text=auto 5 | 6 | ############################################################################### 7 | # Set default behavior for command prompt diff. 8 | # 9 | # This is need for earlier builds of msysgit that does not have it on by 10 | # default for csharp files. 11 | # Note: This is only used by command line 12 | ############################################################################### 13 | #*.cs diff=csharp 14 | 15 | ############################################################################### 16 | # Set the merge driver for project and solution files 17 | # 18 | # Merging from the command prompt will add diff markers to the files if there 19 | # are conflicts (Merging from VS is not affected by the settings below, in VS 20 | # the diff markers are never inserted). Diff markers may cause the following 21 | # file extensions to fail to load in VS. An alternative would be to treat 22 | # these files as binary and thus will always conflict and require user 23 | # intervention with every merge. To do so, just uncomment the entries below 24 | ############################################################################### 25 | #*.sln merge=binary 26 | #*.csproj merge=binary 27 | #*.vbproj merge=binary 28 | #*.vcxproj merge=binary 29 | #*.vcproj merge=binary 30 | #*.dbproj merge=binary 31 | #*.fsproj merge=binary 32 | #*.lsproj merge=binary 33 | #*.wixproj merge=binary 34 | #*.modelproj merge=binary 35 | #*.sqlproj merge=binary 36 | #*.wwaproj merge=binary 37 | 38 | ############################################################################### 39 | # behavior for image files 40 | # 41 | # image files are treated as binary by default. 42 | ############################################################################### 43 | #*.jpg binary 44 | #*.png binary 45 | #*.gif binary 46 | 47 | ############################################################################### 48 | # diff behavior for common document formats 49 | # 50 | # Convert binary document formats to text before diffing them. This feature 51 | # is only available from the command line. Turn it on by uncommenting the 52 | # entries below. 53 | ############################################################################### 54 | #*.doc diff=astextplain 55 | #*.DOC diff=astextplain 56 | #*.docx diff=astextplain 57 | #*.DOCX diff=astextplain 58 | #*.dot diff=astextplain 59 | #*.DOT diff=astextplain 60 | #*.pdf diff=astextplain 61 | #*.PDF diff=astextplain 62 | #*.rtf diff=astextplain 63 | #*.RTF diff=astextplain 64 | -------------------------------------------------------------------------------- /src/Galaxy.Libra.DapperExtensions/DapperImpl/IDapperImplementor.cs: -------------------------------------------------------------------------------- 1 | using Galaxy.Libra.DapperExtensions.Predicate; 2 | using Galaxy.Libra.DapperExtensions.Sql; 3 | using System; 4 | using System.Collections.Generic; 5 | using System.Data; 6 | using System.Linq.Expressions; 7 | 8 | namespace Galaxy.Libra.DapperExtensions.DapperImpl 9 | { 10 | public interface IDapperImplementor 11 | { 12 | ISqlGenerator SqlGenerator { get; } 13 | T Get(IDbConnection connection, dynamic id, IDbTransaction transaction, int? commandTimeout) where T : class; 14 | void Insert(IDbConnection connection, IEnumerable entities, IDbTransaction transaction, int? commandTimeout) where T : class; 15 | dynamic Insert(IDbConnection connection, T entity, IDbTransaction transaction, int? commandTimeout) where T : class; 16 | bool Update(IDbConnection connection, T entity, IDbTransaction transaction, int? commandTimeout) where T : class; 17 | bool Delete(IDbConnection connection, T entity, IDbTransaction transaction, int? commandTimeout) where T : class; 18 | bool Delete(IDbConnection connection, object predicate, IDbTransaction transaction, int? commandTimeout) where T : class; 19 | bool Delete(IDbConnection connection, Expression> expression, IDbTransaction transaction, int? commandTimeout) where T : class; 20 | IEnumerable GetList(IDbConnection connection, object predicate, IList sort, IDbTransaction transaction, int? commandTimeout, bool buffered) where T : class; 21 | IEnumerable GetList(IDbConnection connection, Expression> expression, IList sort, IDbTransaction transaction, int? commandTimeout, bool buffered) where T : class; 22 | IEnumerable GetPage(IDbConnection connection, object predicate, IList sort, int page, int resultsPerPage, IDbTransaction transaction, int? commandTimeout, bool buffered) where T : class; 23 | IEnumerable GetPage(IDbConnection connection, Expression> expression, IList sort, int page, int resultsPerPage, IDbTransaction transaction, int? commandTimeout, bool buffered) where T : class; 24 | IEnumerable GetSet(IDbConnection connection, object predicate, IList sort, int firstResult, int maxResults, IDbTransaction transaction, int? commandTimeout, bool buffered) where T : class; 25 | IEnumerable GetSet(IDbConnection connection, Expression> expression, IList sort, int firstResult, int maxResults, IDbTransaction transaction, int? commandTimeout, bool buffered) where T : class; 26 | int Count(IDbConnection connection, object predicate, IDbTransaction transaction, int? commandTimeout) where T : class; 27 | int Count(IDbConnection connection, Expression> expression, IDbTransaction transaction, int? commandTimeout) where T : class; 28 | IMultipleResultReader GetMultiple(IDbConnection connection, GetMultiplePredicate predicate, IDbTransaction transaction, int? commandTimeout); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/Galaxy.Libra.DapperExtensions.Test/PredicateConverTest.cs: -------------------------------------------------------------------------------- 1 | using Galaxy.Libra.DapperExtensions.Predicate; 2 | using Galaxy.Libra.DapperExtensions.PredicateConver; 3 | using Galaxy.Libra.DapperExtensions.Test.Entity; 4 | using System; 5 | using System.Collections.Generic; 6 | using System.Linq.Expressions; 7 | using Xunit; 8 | 9 | namespace Galaxy.Libra.DapperExtensions.Test 10 | { 11 | public class PredicateConverTest 12 | { 13 | [Fact] 14 | public void TestBase() 15 | { 16 | IPredicate p1 = ExpressionPredicateConvert.GetExpressionPredicate(u => u.Id != 1); 17 | FieldPredicate f1 = p1 as FieldPredicate; 18 | Assert.True(f1.Operator == Operator.Eq); 19 | Assert.True(f1.Not); 20 | 21 | IPredicate pGe = ExpressionPredicateConvert.GetExpressionPredicate(u => u.Id >= 1); 22 | FieldPredicate fGe = pGe as FieldPredicate; 23 | Assert.True(fGe.Operator == Operator.Ge); 24 | } 25 | 26 | [Fact] 27 | public void TestLike() 28 | { 29 | IPredicate p1 = ExpressionPredicateConvert.GetExpressionPredicate(u => u.Name.Contains("1")); 30 | FieldPredicate f1 = p1 as FieldPredicate; 31 | Assert.True(f1.Operator == Operator.Like); 32 | Assert.True(f1.Value.ToString() == "%1%"); 33 | 34 | IPredicate p2 = ExpressionPredicateConvert.GetExpressionPredicate(u => u.Name.StartsWith("1")); 35 | FieldPredicate f2 = p2 as FieldPredicate; 36 | Assert.True(f2.Operator == Operator.Like); 37 | Assert.True(f2.Value.ToString() == "1%"); 38 | 39 | IPredicate p3 = ExpressionPredicateConvert.GetExpressionPredicate(u => u.Name.EndsWith("1")); 40 | FieldPredicate f3 = p3 as FieldPredicate; 41 | Assert.True(f3.Operator == Operator.Like); 42 | Assert.True(f3.Value.ToString() == "%1"); 43 | } 44 | 45 | [Fact] 46 | public void TestIn() 47 | { 48 | List valueList = new List() { "1", "2", "3" }; 49 | IPredicate p = ExpressionPredicateConvert.GetExpressionPredicate(u => valueList.Contains(u.Name)); 50 | FieldPredicate f = p as FieldPredicate; 51 | Assert.True(f.Operator == Operator.Eq); 52 | Assert.True((f.Value as List).Count == 3); 53 | 54 | IPredicate p2 = ExpressionPredicateConvert.GetExpressionPredicate(u => !valueList.Contains(u.Name)); 55 | FieldPredicate f2 = p2 as FieldPredicate; 56 | Assert.True(f.Not == true); 57 | } 58 | 59 | [Fact] 60 | public void TestGroup() 61 | { 62 | IPredicate p = ExpressionPredicateConvert.GetExpressionPredicate(u => u.Id == 1 || (u.Id == 2 && u.Name.Contains("1"))); 63 | FieldPredicate f = (p as IPredicateGroup).Predicates[0] as FieldPredicate; 64 | Assert.True(System.Convert.ToInt32(f.Value) == 1); 65 | Assert.True((p as IPredicateGroup).Operator == GroupOperator.Or); 66 | Expression> expr = u => u.Id == 1 || (u.Id == 2 && u.Name.Contains("1")); 67 | } 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /src/Galaxy.Libra.DapperExtensions/DapperImpl/DapperImplementorGetMultiple.cs: -------------------------------------------------------------------------------- 1 | using Dapper; 2 | using Galaxy.Libra.DapperExtensions.Mapper; 3 | using Galaxy.Libra.DapperExtensions.Predicate; 4 | using System.Collections.Generic; 5 | using System.Data; 6 | using System.Text; 7 | 8 | namespace Galaxy.Libra.DapperExtensions.DapperImpl 9 | { 10 | public partial class DapperImplementor 11 | { 12 | public IMultipleResultReader GetMultiple(IDbConnection connection, GetMultiplePredicate predicate, IDbTransaction transaction, int? commandTimeout) 13 | { 14 | if (SqlGenerator.SupportsMultipleStatements()) 15 | { 16 | return GetMultipleByBatch(connection, predicate, transaction, commandTimeout); 17 | } 18 | 19 | return GetMultipleBySequence(connection, predicate, transaction, commandTimeout); 20 | } 21 | 22 | protected GridReaderResultReader GetMultipleByBatch(IDbConnection connection, GetMultiplePredicate predicate, IDbTransaction transaction, int? commandTimeout) 23 | { 24 | Dictionary parameters = new Dictionary(); 25 | StringBuilder sql = new StringBuilder(); 26 | foreach (var item in predicate.Items) 27 | { 28 | IClassMapper classMap = SqlGenerator.Configuration.GetMap(item.Type); 29 | IPredicate itemPredicate = item.Value as IPredicate; 30 | if (itemPredicate == null && item.Value != null) 31 | { 32 | itemPredicate = GetPredicate(classMap, item.Value); 33 | } 34 | 35 | sql.AppendLine(SqlGenerator.Select(classMap, itemPredicate, item.Sort, parameters) + SqlGenerator.Configuration.Dialect.BatchSeperator); 36 | } 37 | 38 | DynamicParameters dynamicParameters = new DynamicParameters(); 39 | foreach (var parameter in parameters) 40 | { 41 | dynamicParameters.Add(parameter.Key, parameter.Value); 42 | } 43 | 44 | SqlMapper.GridReader grid = connection.QueryMultiple(sql.ToString(), dynamicParameters, transaction, commandTimeout, CommandType.Text); 45 | return new GridReaderResultReader(grid); 46 | } 47 | 48 | protected SequenceReaderResultReader GetMultipleBySequence(IDbConnection connection, GetMultiplePredicate predicate, IDbTransaction transaction, int? commandTimeout) 49 | { 50 | IList items = new List(); 51 | foreach (var item in predicate.Items) 52 | { 53 | Dictionary parameters = new Dictionary(); 54 | IClassMapper classMap = SqlGenerator.Configuration.GetMap(item.Type); 55 | IPredicate itemPredicate = item.Value as IPredicate; 56 | if (itemPredicate == null && item.Value != null) 57 | { 58 | itemPredicate = GetPredicate(classMap, item.Value); 59 | } 60 | 61 | string sql = SqlGenerator.Select(classMap, itemPredicate, item.Sort, parameters); 62 | DynamicParameters dynamicParameters = new DynamicParameters(); 63 | foreach (var parameter in parameters) 64 | { 65 | dynamicParameters.Add(parameter.Key, parameter.Value); 66 | } 67 | 68 | SqlMapper.GridReader queryResult = connection.QueryMultiple(sql, dynamicParameters, transaction, commandTimeout, CommandType.Text); 69 | items.Add(queryResult); 70 | } 71 | 72 | return new SequenceReaderResultReader(items); 73 | } 74 | } 75 | } 76 | -------------------------------------------------------------------------------- /src/Galaxy.Libra.DapperExtensions/DapperImpl/DapperImplementorInsert.cs: -------------------------------------------------------------------------------- 1 | using Dapper; 2 | using Galaxy.Libra.DapperExtensions.Mapper; 3 | using System; 4 | using System.Collections.Generic; 5 | using System.Data; 6 | using System.Dynamic; 7 | using System.Linq; 8 | 9 | namespace Galaxy.Libra.DapperExtensions.DapperImpl 10 | { 11 | public partial class DapperImplementor 12 | { 13 | public void Insert(IDbConnection connection, IEnumerable entities, IDbTransaction transaction, int? commandTimeout) where T : class 14 | { 15 | IClassMapper classMap = SqlGenerator.Configuration.GetMap(); 16 | var properties = classMap.Properties.Where(p => p.KeyType != KeyType.NotAKey); 17 | 18 | foreach (var e in entities) 19 | { 20 | foreach (var column in properties) 21 | { 22 | if (column.KeyType == KeyType.Guid) 23 | { 24 | Guid comb = SqlGenerator.Configuration.GetNextGuid(); 25 | column.PropertyInfo.SetValue(e, comb, null); 26 | } 27 | } 28 | } 29 | 30 | string sql = SqlGenerator.Insert(classMap); 31 | 32 | connection.Execute(sql, entities, transaction, commandTimeout, CommandType.Text); 33 | } 34 | 35 | public dynamic Insert(IDbConnection connection, T entity, IDbTransaction transaction, int? commandTimeout) where T : class 36 | { 37 | IClassMapper classMap = SqlGenerator.Configuration.GetMap(); 38 | List nonIdentityKeyProperties = classMap.Properties.Where(p => p.KeyType == KeyType.Guid || p.KeyType == KeyType.Assigned).ToList(); 39 | var identityColumn = classMap.Properties.SingleOrDefault(p => p.KeyType == KeyType.Identity); 40 | foreach (var column in nonIdentityKeyProperties) 41 | { 42 | if (column.KeyType == KeyType.Guid) 43 | { 44 | Guid comb = SqlGenerator.Configuration.GetNextGuid(); 45 | column.PropertyInfo.SetValue(entity, comb, null); 46 | } 47 | } 48 | 49 | IDictionary keyValues = new ExpandoObject(); 50 | string sql = SqlGenerator.Insert(classMap); 51 | if (identityColumn != null) 52 | { 53 | IEnumerable result; 54 | if (SqlGenerator.SupportsMultipleStatements()) 55 | { 56 | sql += SqlGenerator.Configuration.Dialect.BatchSeperator + SqlGenerator.IdentitySql(classMap); 57 | result = connection.Query(sql, entity, transaction, false, commandTimeout, CommandType.Text); 58 | } 59 | else 60 | { 61 | connection.Execute(sql, entity, transaction, commandTimeout, CommandType.Text); 62 | sql = SqlGenerator.IdentitySql(classMap); 63 | result = connection.Query(sql, entity, transaction, false, commandTimeout, CommandType.Text); 64 | } 65 | 66 | long identityValue = result.First(); 67 | int identityInt = Convert.ToInt32(identityValue); 68 | keyValues.Add(identityColumn.Name, identityInt); 69 | identityColumn.PropertyInfo.SetValue(entity, identityInt, null); 70 | } 71 | else 72 | { 73 | connection.Execute(sql, entity, transaction, commandTimeout, CommandType.Text); 74 | } 75 | 76 | foreach (var column in nonIdentityKeyProperties) 77 | { 78 | keyValues.Add(column.Name, column.PropertyInfo.GetValue(entity, null)); 79 | } 80 | 81 | if (keyValues.Count == 1) 82 | { 83 | return keyValues.First().Value; 84 | } 85 | 86 | return keyValues; 87 | } 88 | } 89 | } 90 | -------------------------------------------------------------------------------- /src/Galaxy.Libra.DapperExtensions/EntityRepository/BaseEntityRepository.cs: -------------------------------------------------------------------------------- 1 | using Dapper; 2 | using Galaxy.Libra.DapperExtensions.Predicate; 3 | using System; 4 | using System.Collections.Generic; 5 | using System.Data; 6 | using System.Linq.Expressions; 7 | 8 | namespace Galaxy.Libra.DapperExtensions.EntityRepository 9 | { 10 | public abstract class BaseEntityRepository : IBaseEntityRepository where T : class 11 | { 12 | protected IDbConnection curDbConnection = null; 13 | 14 | #region 增删改 15 | 16 | public virtual dynamic Add(T entity) => Execute(() => curDbConnection.Insert(entity)); 17 | 18 | public virtual bool Update(T entity) => Execute(() => curDbConnection.Update(entity)); 19 | 20 | public virtual bool Delete(Expression> expression) => Execute(() => curDbConnection.Delete(expression)); 21 | 22 | #endregion 23 | 24 | /// 25 | /// 获取,参数为null时,则获取整个表数据 26 | /// 27 | /// 参数示例,如:new { LastName = "Bar", FirstName = "Foo" } 28 | public virtual List GetList(object predicate = null) => Execute(() => curDbConnection.GetList(predicate).AsList()); 29 | 30 | public virtual List GetList(Expression> expression) => Execute(() => curDbConnection.GetList(expression).AsList()); 31 | 32 | /// 33 | /// 获取分页数据 34 | /// 35 | /// 页索引 36 | /// 每页记录数 37 | /// 参数示例,如:new { LastName = "Bar", FirstName = "Foo" }, 更多的请使用Predicates 38 | public virtual List GetPage(int page, int resultsPerPage, IList sort, object predicate = null) 39 | => Execute(() => curDbConnection.GetPage(predicate, sort, page, resultsPerPage).AsList()); 40 | 41 | /// 42 | /// 获取分页数据 43 | /// 44 | /// 页索引 45 | /// 每页记录数 46 | public virtual List GetPage(int page, int resultsPerPage, IList sort, Expression> expression) 47 | => Execute(() => curDbConnection.GetPage(expression, sort, page, resultsPerPage).AsList()); 48 | 49 | /// 50 | /// 数量 51 | /// 52 | /// 参数示例,如:new { LastName = "Bar", FirstName = "Foo" } 53 | /// 54 | public virtual int Count(object predicate = null) => Execute(() => curDbConnection.Count(predicate)); 55 | 56 | /// 57 | /// 数量 58 | /// 59 | /// 参数示例,如:new { LastName = "Bar", FirstName = "Foo" } 60 | /// 61 | public virtual int Count(Expression> expression) => Execute(() => curDbConnection.Count(expression)); 62 | 63 | private R Execute(Func fun) 64 | { 65 | if (curDbConnection != null && fun != null) 66 | { 67 | using (curDbConnection) 68 | { 69 | if (curDbConnection.State != ConnectionState.Open) 70 | curDbConnection.Open(); 71 | 72 | R res = fun(); 73 | 74 | curDbConnection.Close(); 75 | return res; 76 | } 77 | } 78 | 79 | return default(R); 80 | } 81 | 82 | private void ExecuteNoValue(Action action) 83 | { 84 | if (curDbConnection != null && action != null) 85 | { 86 | using (curDbConnection) 87 | { 88 | if (curDbConnection.State != ConnectionState.Open) 89 | curDbConnection.Open(); 90 | 91 | action(); 92 | 93 | curDbConnection.Close(); 94 | } 95 | } 96 | } 97 | } 98 | } 99 | -------------------------------------------------------------------------------- /src/Galaxy.Libra.DapperExtensions/Mapper/PluralizedAutoClassMapper.cs: -------------------------------------------------------------------------------- 1 | using System.Text; 2 | using System.Linq; 3 | using System.Collections.Generic; 4 | using System; 5 | using System.Text.RegularExpressions; 6 | 7 | namespace Galaxy.Libra.DapperExtensions.Mapper 8 | { 9 | /// 10 | /// Automatically maps an entity to a table using a combination of reflection and naming conventions for keys. 11 | /// Identical to AutoClassMapper, but attempts to pluralize table names automatically. 12 | /// Example: Person entity maps to People table 13 | /// 14 | public class PluralizedAutoClassMapper : AutoClassMapper where T : class 15 | { 16 | public override void Table(string tableName) 17 | { 18 | base.Table(Formatting.Pluralize(tableName)); 19 | } 20 | 21 | // Adapted from: http://mattgrande.wordpress.com/2009/10/28/pluralization-helper-for-c/ 22 | public static class Formatting 23 | { 24 | private static readonly IList Unpluralizables = new List { "equipment", "information", "rice", "money", "species", "series", "fish", "sheep", "deer" }; 25 | private static readonly IDictionary Pluralizations = new Dictionary 26 | { 27 | // Start with the rarest cases, and move to the most common 28 | { "person", "people" }, 29 | { "ox", "oxen" }, 30 | { "child", "children" }, 31 | { "foot", "feet" }, 32 | { "tooth", "teeth" }, 33 | { "goose", "geese" }, 34 | // And now the more standard rules. 35 | { "(.*)fe?$", "$1ves" }, // ie, wolf, wife 36 | { "(.*)man$", "$1men" }, 37 | { "(.+[aeiou]y)$", "$1s" }, 38 | { "(.+[^aeiou])y$", "$1ies" }, 39 | { "(.+z)$", "$1zes" }, 40 | { "([m|l])ouse$", "$1ice" }, 41 | { "(.+)(e|i)x$", @"$1ices"}, // ie, Matrix, Index 42 | { "(octop|vir)us$", "$1i"}, 43 | { "(.+(s|x|sh|ch))$", @"$1es"}, 44 | { "(.+)", @"$1s" } 45 | }; 46 | 47 | public static string Pluralize(string singular) 48 | { 49 | if (Unpluralizables.Contains(singular)) 50 | return singular; 51 | 52 | var plural = string.Empty; 53 | 54 | foreach (var pluralization in Pluralizations) 55 | { 56 | if (Regex.IsMatch(singular, pluralization.Key)) 57 | { 58 | plural = Regex.Replace(singular, pluralization.Key, pluralization.Value); 59 | break; 60 | } 61 | } 62 | 63 | return plural; 64 | } 65 | } 66 | } 67 | } -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Galaxy.Libra.DapperExtensions 2 | 一个轻量的Dapper扩展库,基于netcore,支持MySQL,SQLServer等多种常用数据库。 3 | 基于[Dapper-Extensions](https://github.com/tmsmith/Dapper-Extensions)优化,并加入了建库,建表的功能。 4 | 5 | 欢迎会开发的您一起加入,完善本项目,QQ:499053596 6 | 7 | ## 例子 8 | 9 | ### 定义一个实体类 10 | ``` c# 11 | public class User 12 | { 13 | public int Id { get; set; } 14 | 15 | public string Name { get; set; } 16 | 17 | public string Psw { get; set; } 18 | } 19 | ``` 20 | ### 基本使用 21 | 22 | #### 插入 23 | ```c# 24 | using (SqlConnection cn = new SqlConnection(_connectionString)) 25 | { 26 | cn.Open(); 27 | User user = new User { Name = "波多野结衣" , Psw = "123"}; 28 | int id = cn.Insert(user); 29 | cn.Close(); 30 | } 31 | ``` 32 | #### 更新 33 | ``` 34 | using (SqlConnection cn = new SqlConnection(_connectionString)) 35 | { 36 | cn.Open(); 37 | int id = 1; 38 | User user = cn.Get(id); 39 | user.Name = "林志玲"; 40 | cn.Update(user); 41 | cn.Close(); 42 | } 43 | ``` 44 | #### 删除 45 | ```c# 46 | using (SqlConnection cn = new SqlConnection(_connectionString)) 47 | { 48 | cn.Open(); 49 | int id = 1; 50 | User user = cn.Get(id); 51 | cn.Delete(user); 52 | cn.Close(); 53 | } 54 | ``` 55 | #### 基于ID查询 56 | ```c# 57 | using (SqlConnection cn = new SqlConnection(_connectionString)) 58 | { 59 | cn.Open(); 60 | int Id = 1; 61 | Person person = cn.Get(Id); 62 | cn.Close(); 63 | } 64 | ``` 65 | #### 基于动态对象查询 66 | ```c# 67 | using (SqlConnection cn = new SqlConnection(_connectionString)) 68 | { 69 | cn.Open(); 70 | Person person = cn.GetList(new { Name = "波多野结衣" , Psw = "123"}); 71 | cn.Close(); 72 | } 73 | ``` 74 | #### 基于表达式查询 75 | ```c# 76 | using (SqlConnection cn = new SqlConnection(_connectionString)) 77 | { 78 | cn.Open(); 79 | Person person = cn.Get(u => u.Id != 1); 80 | person = cn.GetList(u => u.Name.Contains("1")); //Like查询 81 | person = cn.GetList(u => u.Name.StartsWith("1")); //Like查询 82 | person = cn.GetList(u => u.Name.EndsWith("1")); //Like查询 83 | 84 | List valueList = new List() { "1", "2", "3" }; 85 | person = cn.GetList(u => valueList.Contains(u.Name)); //in查询 86 | person = cn.GetList(u => !valueList.Contains(u.Name)); //not in查询 87 | 88 | person = cn.GetList(u => u.Id == 1 || (u.Id == 2 && u.Name.Contains("1"))); //复合查询 89 | cn.Close(); 90 | } 91 | ``` 92 | #### 基于Predicate查询 93 | ```c# 94 | using (SqlConnection cn = new SqlConnection(_connectionString)) 95 | { 96 | cn.Open(); 97 | var predicate = Predicates.Field(p => p.Name, Operator.Like, "李%"); 98 | IEnumerable list = cn.GetList(predicate); 99 | cn.Close(); 100 | } 101 | ``` 102 | ##### 构建查询条件(基于MySQL) 103 | * 简单查询,包括大于,等于,Like等,生成:(`User`.`Name` LIKE @Name_0) 104 | ```c# 105 | Predicates.Field(p => p.Name, Operator.Like, "李%"); 106 | ``` 107 | * in查询,生成:(`User`.`Name` IN (@Name_0, @Name_1, @Name_2)) 108 | ```c# 109 | List valueList = new List() { "1", "2", "3" }; 110 | Predicates.Field(p => p.Name, Operator.Eq, valueList); 111 | ``` 112 | * between查询,生成:(`User`.`Name` NOT BETWEEN @Name_0 AND @Name_1) 113 | ```c# 114 | Predicates.Between(p => p.Name, new BetweenValues { Value1 = 1, Value2 = 10 }, true); 115 | ``` 116 | * exist查询,生成:(NOT EXISTS (SELECT 1 FROM `User` WHERE (`User`.`Name` LIKE @Name_0))) 117 | ```c# 118 | IFieldPredicate nameFieldPredicate = Predicates.Field(p => p.Name, Operator.Like, "李%"); 119 | Predicates.Exists(nameFieldPredicate, true); 120 | ``` 121 | * 组合查询,生成:(((`User`.`Name` LIKE @Name_0) AND (`User`.`Name` NOT BETWEEN @Name_1 AND @Name_2)) OR (`User`.`Name` LIKE @Name_3)) 122 | ```c# 123 | IList predList = new List(); 124 | predList.Add(Predicates.Field(p => p.Name, Operator.Like, "李%")); 125 | predList.Add(Predicates.Field(p => p.Name, Operator.Eq, valueList)); 126 | IPredicateGroup predGroup1 = Predicates.Group(GroupOperator.And, predList.ToArray()); 127 | 128 | IList predList2 = new List(); 129 | predList2.Add(predGroup1); 130 | predList2.Add(Predicates.Field(p => p.Name, Operator.Like, "张%")); 131 | IPredicateGroup predGroup2 = Predicates.Group(GroupOperator.Or, predList2.ToArray()); 132 | ``` 133 | -------------------------------------------------------------------------------- /src/Galaxy.Libra.DapperExtensions/ReflectionHelper.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Linq.Expressions; 5 | using System.Reflection; 6 | using System.Text; 7 | 8 | namespace Galaxy.Libra.DapperExtensions 9 | { 10 | public static class ReflectionHelper 11 | { 12 | private static List _simpleTypes = new List 13 | { 14 | typeof(byte), 15 | typeof(sbyte), 16 | typeof(short), 17 | typeof(ushort), 18 | typeof(int), 19 | typeof(uint), 20 | typeof(long), 21 | typeof(ulong), 22 | typeof(float), 23 | typeof(double), 24 | typeof(decimal), 25 | typeof(bool), 26 | typeof(string), 27 | typeof(char), 28 | typeof(Guid), 29 | typeof(DateTime), 30 | typeof(DateTimeOffset), 31 | typeof(byte[]) 32 | }; 33 | 34 | public static MemberInfo GetProperty(LambdaExpression lambda) 35 | { 36 | Expression expr = lambda; 37 | for (; ; ) 38 | { 39 | switch (expr.NodeType) 40 | { 41 | case ExpressionType.Lambda: 42 | expr = ((LambdaExpression)expr).Body; 43 | break; 44 | case ExpressionType.Convert: 45 | expr = ((UnaryExpression)expr).Operand; 46 | break; 47 | case ExpressionType.MemberAccess: 48 | MemberExpression memberExpression = (MemberExpression)expr; 49 | MemberInfo mi = memberExpression.Member; 50 | return mi; 51 | default: 52 | return null; 53 | } 54 | } 55 | } 56 | 57 | public static IDictionary GetObjectValues(object obj) 58 | { 59 | IDictionary result = new Dictionary(); 60 | if (obj == null) 61 | { 62 | return result; 63 | } 64 | 65 | 66 | foreach (var propertyInfo in obj.GetType().GetProperties()) 67 | { 68 | string name = propertyInfo.Name; 69 | object value = propertyInfo.GetValue(obj, null); 70 | result[name] = value; 71 | } 72 | 73 | return result; 74 | } 75 | 76 | public static string AppendStrings(this IEnumerable list, string seperator = ", ") 77 | { 78 | return list.Aggregate( 79 | new StringBuilder(), 80 | (sb, s) => (sb.Length == 0 ? sb : sb.Append(seperator)).Append(s), 81 | sb => sb.ToString()); 82 | } 83 | 84 | public static bool IsSimpleType(Type type) 85 | { 86 | Type actualType = type; 87 | if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>)) 88 | { 89 | actualType = type.GetGenericArguments()[0]; 90 | } 91 | 92 | return _simpleTypes.Contains(actualType); 93 | } 94 | 95 | public static string GetParameterName(this IDictionary parameters, string parameterName, char parameterPrefix) 96 | { 97 | return string.Format("{0}{1}_{2}", parameterPrefix, parameterName, parameters.Count); 98 | } 99 | 100 | public static string SetParameterName(this IDictionary parameters, string parameterName, object value, char parameterPrefix) 101 | { 102 | string name = parameters.GetParameterName(parameterName, parameterPrefix); 103 | parameters.Add(name, value); 104 | return name; 105 | } 106 | } 107 | } -------------------------------------------------------------------------------- /src/Galaxy.Libra.DapperExtensions/DapperExtensionsConfiguration.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Concurrent; 3 | using System.Collections.Generic; 4 | using System.Linq; 5 | using System.Reflection; 6 | using System.Text; 7 | using Galaxy.Libra.DapperExtensions.Mapper; 8 | using Galaxy.Libra.DapperExtensions.Sql; 9 | 10 | namespace Galaxy.Libra.DapperExtensions 11 | { 12 | public interface IDapperExtensionsConfiguration 13 | { 14 | Type DefaultMapper { get; } 15 | IList MappingAssemblies { get; } 16 | ISqlDialect Dialect { get; } 17 | IClassMapper GetMap(Type entityType); 18 | IClassMapper GetMap() where T : class; 19 | void ClearCache(); 20 | Guid GetNextGuid(); 21 | } 22 | 23 | public class DapperExtensionsConfiguration : IDapperExtensionsConfiguration 24 | { 25 | private readonly ConcurrentDictionary _classMaps = new ConcurrentDictionary(); 26 | 27 | public DapperExtensionsConfiguration() 28 | : this(typeof(AutoClassMapper<>), new List(), new SqlServerDialect()) 29 | { 30 | } 31 | 32 | 33 | public DapperExtensionsConfiguration(Type defaultMapper, IList mappingAssemblies, ISqlDialect sqlDialect) 34 | { 35 | DefaultMapper = defaultMapper; 36 | MappingAssemblies = mappingAssemblies ?? new List(); 37 | Dialect = sqlDialect; 38 | } 39 | 40 | public Type DefaultMapper { get; private set; } 41 | public IList MappingAssemblies { get; private set; } 42 | public ISqlDialect Dialect { get; private set; } 43 | 44 | public IClassMapper GetMap(Type entityType) 45 | { 46 | IClassMapper map; 47 | if (!_classMaps.TryGetValue(entityType, out map)) 48 | { 49 | Type mapType = GetMapType(entityType); 50 | if (mapType == null) 51 | { 52 | mapType = DefaultMapper.MakeGenericType(entityType); 53 | } 54 | 55 | map = Activator.CreateInstance(mapType) as IClassMapper; 56 | _classMaps[entityType] = map; 57 | } 58 | 59 | return map; 60 | } 61 | 62 | public IClassMapper GetMap() where T : class 63 | { 64 | return GetMap(typeof (T)); 65 | } 66 | 67 | public void ClearCache() 68 | { 69 | _classMaps.Clear(); 70 | } 71 | 72 | public Guid GetNextGuid() 73 | { 74 | byte[] b = Guid.NewGuid().ToByteArray(); 75 | DateTime dateTime = new DateTime(1900, 1, 1); 76 | DateTime now = DateTime.Now; 77 | TimeSpan timeSpan = new TimeSpan(now.Ticks - dateTime.Ticks); 78 | TimeSpan timeOfDay = now.TimeOfDay; 79 | byte[] bytes1 = BitConverter.GetBytes(timeSpan.Days); 80 | byte[] bytes2 = BitConverter.GetBytes((long)(timeOfDay.TotalMilliseconds / 3.333333)); 81 | Array.Reverse(bytes1); 82 | Array.Reverse(bytes2); 83 | Array.Copy(bytes1, bytes1.Length - 2, b, b.Length - 6, 2); 84 | Array.Copy(bytes2, bytes2.Length - 4, b, b.Length - 4, 4); 85 | return new Guid(b); 86 | } 87 | 88 | protected virtual Type GetMapType(Type entityType) 89 | { 90 | Func getType = a => 91 | { 92 | Type[] types = a.GetTypes(); 93 | return (from type in types 94 | let interfaceType = type.GetInterface(typeof(IClassMapper<>).FullName) 95 | where 96 | interfaceType != null && 97 | interfaceType.GetGenericArguments()[0] == entityType 98 | select type).SingleOrDefault(); 99 | }; 100 | 101 | Type result = getType(entityType.Assembly); 102 | if (result != null) 103 | { 104 | return result; 105 | } 106 | 107 | foreach (var mappingAssembly in MappingAssemblies) 108 | { 109 | result = getType(mappingAssembly); 110 | if (result != null) 111 | { 112 | return result; 113 | } 114 | } 115 | 116 | return getType(entityType.Assembly); 117 | } 118 | } 119 | } -------------------------------------------------------------------------------- /src/Galaxy.Libra.DapperExtensions/Sql/SqlDialectBase.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | 6 | namespace Galaxy.Libra.DapperExtensions.Sql 7 | { 8 | public interface ISqlDialect 9 | { 10 | char OpenQuote { get; } 11 | char CloseQuote { get; } 12 | string BatchSeperator { get; } 13 | bool SupportsMultipleStatements { get; } 14 | char ParameterPrefix { get; } 15 | string EmptyExpression { get; } 16 | string GetTableName(string schemaName, string tableName, string alias); 17 | string GetColumnName(string prefix, string columnName, string alias); 18 | string GetIdentitySql(string tableName); 19 | string GetPagingSql(string sql, int page, int resultsPerPage, IDictionary parameters); 20 | string GetSetSql(string sql, int firstResult, int maxResults, IDictionary parameters); 21 | bool IsQuoted(string value); 22 | string QuoteString(string value); 23 | } 24 | 25 | public abstract class SqlDialectBase : ISqlDialect 26 | { 27 | public virtual char OpenQuote 28 | { 29 | get { return '"'; } 30 | } 31 | 32 | public virtual char CloseQuote 33 | { 34 | get { return '"'; } 35 | } 36 | 37 | public virtual string BatchSeperator 38 | { 39 | get { return ";" + Environment.NewLine; } 40 | } 41 | 42 | public virtual bool SupportsMultipleStatements 43 | { 44 | get { return true; } 45 | } 46 | 47 | public virtual char ParameterPrefix 48 | { 49 | get 50 | { 51 | return '@'; 52 | } 53 | } 54 | 55 | public string EmptyExpression 56 | { 57 | get 58 | { 59 | return "1=1"; 60 | } 61 | } 62 | 63 | public virtual string GetTableName(string schemaName, string tableName, string alias) 64 | { 65 | if (string.IsNullOrWhiteSpace(tableName)) 66 | { 67 | throw new ArgumentNullException("TableName", "tableName cannot be null or empty."); 68 | } 69 | 70 | StringBuilder result = new StringBuilder(); 71 | if (!string.IsNullOrWhiteSpace(schemaName)) 72 | { 73 | result.AppendFormat(QuoteString(schemaName) + "."); 74 | } 75 | 76 | result.AppendFormat(QuoteString(tableName)); 77 | 78 | if (!string.IsNullOrWhiteSpace(alias)) 79 | { 80 | result.AppendFormat(" AS {0}", QuoteString(alias)); 81 | } 82 | return result.ToString(); 83 | } 84 | 85 | public virtual string GetColumnName(string prefix, string columnName, string alias) 86 | { 87 | if (string.IsNullOrWhiteSpace(columnName)) 88 | { 89 | throw new ArgumentNullException("ColumnName", "columnName cannot be null or empty."); 90 | } 91 | 92 | StringBuilder result = new StringBuilder(); 93 | if (!string.IsNullOrWhiteSpace(prefix)) 94 | { 95 | result.AppendFormat(QuoteString(prefix) + "."); 96 | } 97 | 98 | result.AppendFormat(QuoteString(columnName)); 99 | 100 | if (!string.IsNullOrWhiteSpace(alias)) 101 | { 102 | result.AppendFormat(" AS {0}", QuoteString(alias)); 103 | } 104 | 105 | return result.ToString(); 106 | } 107 | 108 | public abstract string GetIdentitySql(string tableName); 109 | public abstract string GetPagingSql(string sql, int page, int resultsPerPage, IDictionary parameters); 110 | public abstract string GetSetSql(string sql, int firstResult, int maxResults, IDictionary parameters); 111 | 112 | public virtual bool IsQuoted(string value) 113 | { 114 | if (value.Trim()[0] == OpenQuote) 115 | { 116 | return value.Trim().Last() == CloseQuote; 117 | } 118 | 119 | return false; 120 | } 121 | 122 | public virtual string QuoteString(string value) 123 | { 124 | return IsQuoted(value) ? value : string.Format("{0}{1}{2}", OpenQuote, value.Trim(), CloseQuote); 125 | } 126 | 127 | public virtual string UnQuoteString(string value) 128 | { 129 | return IsQuoted(value) ? value.Substring(1, value.Length - 2) : value; 130 | } 131 | } 132 | } -------------------------------------------------------------------------------- /src/Galaxy.Libra.DapperExtensions/Sql/SqlServerDialect.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | 6 | namespace Galaxy.Libra.DapperExtensions.Sql 7 | { 8 | public class SqlServerDialect : SqlDialectBase 9 | { 10 | public override char OpenQuote 11 | { 12 | get { return '['; } 13 | } 14 | 15 | public override char CloseQuote 16 | { 17 | get { return ']'; } 18 | } 19 | 20 | public override string GetIdentitySql(string tableName) 21 | { 22 | return string.Format("SELECT CAST(SCOPE_IDENTITY() AS BIGINT) AS [Id]"); 23 | } 24 | 25 | public override string GetPagingSql(string sql, int page, int resultsPerPage, IDictionary parameters) 26 | { 27 | int startValue = (page * resultsPerPage) + 1; 28 | return GetSetSql(sql, startValue, resultsPerPage, parameters); 29 | } 30 | 31 | public override string GetSetSql(string sql, int firstResult, int maxResults, IDictionary parameters) 32 | { 33 | if (string.IsNullOrEmpty(sql)) 34 | { 35 | throw new ArgumentNullException("SQL"); 36 | } 37 | 38 | if (parameters == null) 39 | { 40 | throw new ArgumentNullException("Parameters"); 41 | } 42 | 43 | int selectIndex = GetSelectEnd(sql) + 1; 44 | string orderByClause = GetOrderByClause(sql); 45 | if (orderByClause == null) 46 | { 47 | orderByClause = "ORDER BY CURRENT_TIMESTAMP"; 48 | } 49 | 50 | 51 | string projectedColumns = GetColumnNames(sql).Aggregate(new StringBuilder(), (sb, s) => (sb.Length == 0 ? sb : sb.Append(", ")).Append(GetColumnName("_proj", s, null)), sb => sb.ToString()); 52 | string newSql = sql 53 | .Replace(" " + orderByClause, string.Empty) 54 | .Insert(selectIndex, string.Format("ROW_NUMBER() OVER(ORDER BY {0}) AS {1}, ", orderByClause.Substring(9), GetColumnName(null, "_row_number", null))); 55 | 56 | string result = string.Format("SELECT TOP({0}) {1} FROM ({2}) [_proj] WHERE {3} >= @_pageStartRow ORDER BY {3}", 57 | maxResults, projectedColumns.Trim(), newSql, GetColumnName("_proj", "_row_number", null)); 58 | 59 | parameters.Add("@_pageStartRow", firstResult); 60 | return result; 61 | } 62 | 63 | protected string GetOrderByClause(string sql) 64 | { 65 | int orderByIndex = sql.LastIndexOf(" ORDER BY ", StringComparison.InvariantCultureIgnoreCase); 66 | if (orderByIndex == -1) 67 | { 68 | return null; 69 | } 70 | 71 | string result = sql.Substring(orderByIndex).Trim(); 72 | 73 | int whereIndex = result.IndexOf(" WHERE ", StringComparison.InvariantCultureIgnoreCase); 74 | if (whereIndex == -1) 75 | { 76 | return result; 77 | } 78 | 79 | return result.Substring(0, whereIndex).Trim(); 80 | } 81 | 82 | protected int GetFromStart(string sql) 83 | { 84 | int selectCount = 0; 85 | string[] words = sql.Split(' '); 86 | int fromIndex = 0; 87 | foreach (var word in words) 88 | { 89 | if (word.Equals("SELECT", StringComparison.InvariantCultureIgnoreCase)) 90 | { 91 | selectCount++; 92 | } 93 | 94 | if (word.Equals("FROM", StringComparison.InvariantCultureIgnoreCase)) 95 | { 96 | selectCount--; 97 | if (selectCount == 0) 98 | { 99 | break; 100 | } 101 | } 102 | 103 | fromIndex += word.Length + 1; 104 | } 105 | 106 | return fromIndex; 107 | } 108 | 109 | protected virtual int GetSelectEnd(string sql) 110 | { 111 | if (sql.StartsWith("SELECT DISTINCT", StringComparison.InvariantCultureIgnoreCase)) 112 | { 113 | return 15; 114 | } 115 | 116 | if (sql.StartsWith("SELECT", StringComparison.InvariantCultureIgnoreCase)) 117 | { 118 | return 6; 119 | } 120 | 121 | throw new ArgumentException("SQL must be a SELECT statement.", "sql"); 122 | } 123 | 124 | protected virtual IList GetColumnNames(string sql) 125 | { 126 | int start = GetSelectEnd(sql); 127 | int stop = GetFromStart(sql); 128 | string[] columnSql = sql.Substring(start, stop - start).Split(','); 129 | List result = new List(); 130 | foreach (string c in columnSql) 131 | { 132 | int index = c.IndexOf(" AS ", StringComparison.InvariantCultureIgnoreCase); 133 | if (index > 0) 134 | { 135 | result.Add(c.Substring(index + 4).Trim()); 136 | continue; 137 | } 138 | 139 | string[] colParts = c.Split('.'); 140 | result.Add(colParts[colParts.Length - 1].Trim()); 141 | } 142 | 143 | return result; 144 | } 145 | } 146 | } -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | 4 | # User-specific files 5 | *.suo 6 | *.user 7 | *.userosscache 8 | *.sln.docstates 9 | 10 | # User-specific files (MonoDevelop/Xamarin Studio) 11 | *.userprefs 12 | 13 | # Build results 14 | [Dd]ebug/ 15 | [Dd]ebugPublic/ 16 | [Rr]elease/ 17 | [Rr]eleases/ 18 | x64/ 19 | x86/ 20 | bld/ 21 | [Bb]in/ 22 | [Oo]bj/ 23 | [Ll]og/ 24 | 25 | # Visual Studio 2015 cache/options directory 26 | .vs/ 27 | # Uncomment if you have tasks that create the project's static files in wwwroot 28 | #wwwroot/ 29 | 30 | # MSTest test Results 31 | [Tt]est[Rr]esult*/ 32 | [Bb]uild[Ll]og.* 33 | 34 | # NUNIT 35 | *.VisualState.xml 36 | TestResult.xml 37 | 38 | # Build Results of an ATL Project 39 | [Dd]ebugPS/ 40 | [Rr]eleasePS/ 41 | dlldata.c 42 | 43 | # DNX 44 | project.lock.json 45 | project.fragment.lock.json 46 | artifacts/ 47 | 48 | *_i.c 49 | *_p.c 50 | *_i.h 51 | *.ilk 52 | *.meta 53 | *.obj 54 | *.pch 55 | *.pdb 56 | *.pgc 57 | *.pgd 58 | *.rsp 59 | *.sbr 60 | *.tlb 61 | *.tli 62 | *.tlh 63 | *.tmp 64 | *.tmp_proj 65 | *.log 66 | *.vspscc 67 | *.vssscc 68 | .builds 69 | *.pidb 70 | *.svclog 71 | *.scc 72 | 73 | # Chutzpah Test files 74 | _Chutzpah* 75 | 76 | # Visual C++ cache files 77 | ipch/ 78 | *.aps 79 | *.ncb 80 | *.opendb 81 | *.opensdf 82 | *.sdf 83 | *.cachefile 84 | *.VC.db 85 | *.VC.VC.opendb 86 | 87 | # Visual Studio profiler 88 | *.psess 89 | *.vsp 90 | *.vspx 91 | *.sap 92 | 93 | # TFS 2012 Local Workspace 94 | $tf/ 95 | 96 | # Guidance Automation Toolkit 97 | *.gpState 98 | 99 | # ReSharper is a .NET coding add-in 100 | _ReSharper*/ 101 | *.[Rr]e[Ss]harper 102 | *.DotSettings.user 103 | 104 | # JustCode is a .NET coding add-in 105 | .JustCode 106 | 107 | # TeamCity is a build add-in 108 | _TeamCity* 109 | 110 | # DotCover is a Code Coverage Tool 111 | *.dotCover 112 | 113 | # NCrunch 114 | _NCrunch_* 115 | .*crunch*.local.xml 116 | nCrunchTemp_* 117 | 118 | # MightyMoose 119 | *.mm.* 120 | AutoTest.Net/ 121 | 122 | # Web workbench (sass) 123 | .sass-cache/ 124 | 125 | # Installshield output folder 126 | [Ee]xpress/ 127 | 128 | # DocProject is a documentation generator add-in 129 | DocProject/buildhelp/ 130 | DocProject/Help/*.HxT 131 | DocProject/Help/*.HxC 132 | DocProject/Help/*.hhc 133 | DocProject/Help/*.hhk 134 | DocProject/Help/*.hhp 135 | DocProject/Help/Html2 136 | DocProject/Help/html 137 | 138 | # Click-Once directory 139 | publish/ 140 | 141 | # Publish Web Output 142 | *.[Pp]ublish.xml 143 | *.azurePubxml 144 | # TODO: Comment the next line if you want to checkin your web deploy settings 145 | # but database connection strings (with potential passwords) will be unencrypted 146 | #*.pubxml 147 | *.publishproj 148 | 149 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 150 | # checkin your Azure Web App publish settings, but sensitive information contained 151 | # in these scripts will be unencrypted 152 | PublishScripts/ 153 | 154 | # NuGet Packages 155 | *.nupkg 156 | # The packages folder can be ignored because of Package Restore 157 | **/packages/* 158 | # except build/, which is used as an MSBuild target. 159 | !**/packages/build/ 160 | # Uncomment if necessary however generally it will be regenerated when needed 161 | #!**/packages/repositories.config 162 | # NuGet v3's project.json files produces more ignoreable files 163 | *.nuget.props 164 | *.nuget.targets 165 | 166 | # Microsoft Azure Build Output 167 | csx/ 168 | *.build.csdef 169 | 170 | # Microsoft Azure Emulator 171 | ecf/ 172 | rcf/ 173 | 174 | # Windows Store app package directories and files 175 | AppPackages/ 176 | BundleArtifacts/ 177 | Package.StoreAssociation.xml 178 | _pkginfo.txt 179 | 180 | # Visual Studio cache files 181 | # files ending in .cache can be ignored 182 | *.[Cc]ache 183 | # but keep track of directories ending in .cache 184 | !*.[Cc]ache/ 185 | 186 | # Others 187 | ClientBin/ 188 | ~$* 189 | *~ 190 | *.dbmdl 191 | *.dbproj.schemaview 192 | *.jfm 193 | *.pfx 194 | *.publishsettings 195 | node_modules/ 196 | orleans.codegen.cs 197 | 198 | # Since there are multiple workflows, uncomment next line to ignore bower_components 199 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 200 | #bower_components/ 201 | 202 | # RIA/Silverlight projects 203 | Generated_Code/ 204 | 205 | # Backup & report files from converting an old project file 206 | # to a newer Visual Studio version. Backup files are not needed, 207 | # because we have git ;-) 208 | _UpgradeReport_Files/ 209 | Backup*/ 210 | UpgradeLog*.XML 211 | UpgradeLog*.htm 212 | 213 | # SQL Server files 214 | *.mdf 215 | *.ldf 216 | 217 | # Business Intelligence projects 218 | *.rdl.data 219 | *.bim.layout 220 | *.bim_*.settings 221 | 222 | # Microsoft Fakes 223 | FakesAssemblies/ 224 | 225 | # GhostDoc plugin setting file 226 | *.GhostDoc.xml 227 | 228 | # Node.js Tools for Visual Studio 229 | .ntvs_analysis.dat 230 | 231 | # Visual Studio 6 build log 232 | *.plg 233 | 234 | # Visual Studio 6 workspace options file 235 | *.opt 236 | 237 | # Visual Studio LightSwitch build output 238 | **/*.HTMLClient/GeneratedArtifacts 239 | **/*.DesktopClient/GeneratedArtifacts 240 | **/*.DesktopClient/ModelManifest.xml 241 | **/*.Server/GeneratedArtifacts 242 | **/*.Server/ModelManifest.xml 243 | _Pvt_Extensions 244 | 245 | # Paket dependency manager 246 | .paket/paket.exe 247 | paket-files/ 248 | 249 | # FAKE - F# Make 250 | .fake/ 251 | 252 | # JetBrains Rider 253 | .idea/ 254 | *.sln.iml 255 | 256 | # CodeRush 257 | .cr/ 258 | 259 | # Python Tools for Visual Studio (PTVS) 260 | __pycache__/ 261 | *.pyc -------------------------------------------------------------------------------- /src/Galaxy.Libra.DapperExtensions/Predicate/Predicates.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections; 3 | using System.Collections.Generic; 4 | using System.Linq; 5 | using System.Linq.Expressions; 6 | using System.Reflection; 7 | using System.Text; 8 | using Galaxy.Libra.DapperExtensions.Mapper; 9 | using Galaxy.Libra.DapperExtensions.Sql; 10 | 11 | namespace Galaxy.Libra.DapperExtensions.Predicate 12 | { 13 | public static class Predicates 14 | { 15 | /// 16 | /// Factory method that creates a new IFieldPredicate predicate: [FieldName] [Operator] [Value]. 17 | /// Example: WHERE FirstName = 'Foo' 18 | /// 19 | /// The type of the entity. 20 | /// An expression that returns the left operand [FieldName]. 21 | /// The comparison operator. 22 | /// The value for the predicate. 23 | /// Effectively inverts the comparison operator. Example: WHERE FirstName <> 'Foo'. 24 | /// An instance of IFieldPredicate. 25 | public static IFieldPredicate Field(Expression> expression, Operator op, object value, bool not = false) where T : class 26 | { 27 | PropertyInfo propertyInfo = ReflectionHelper.GetProperty(expression) as PropertyInfo; 28 | return new FieldPredicate 29 | { 30 | PropertyName = propertyInfo.Name, 31 | Operator = op, 32 | Value = value, 33 | Not = not 34 | }; 35 | } 36 | 37 | /// 38 | /// Factory method that creates a new IPropertyPredicate predicate: [FieldName1] [Operator] [FieldName2] 39 | /// Example: WHERE FirstName = LastName 40 | /// 41 | /// The type of the entity for the left operand. 42 | /// The type of the entity for the right operand. 43 | /// An expression that returns the left operand [FieldName1]. 44 | /// The comparison operator. 45 | /// An expression that returns the right operand [FieldName2]. 46 | /// Effectively inverts the comparison operator. Example: WHERE FirstName <> LastName 47 | /// An instance of IPropertyPredicate. 48 | public static IPropertyPredicate Property(Expression> expression, Operator op, Expression> expression2, bool not = false) 49 | where T : class 50 | where T2 : class 51 | { 52 | PropertyInfo propertyInfo = ReflectionHelper.GetProperty(expression) as PropertyInfo; 53 | PropertyInfo propertyInfo2 = ReflectionHelper.GetProperty(expression2) as PropertyInfo; 54 | return new PropertyPredicate 55 | { 56 | PropertyName = propertyInfo.Name, 57 | PropertyName2 = propertyInfo2.Name, 58 | Operator = op, 59 | Not = not 60 | }; 61 | } 62 | 63 | /// 64 | /// Factory method that creates a new IPredicateGroup predicate. 65 | /// Predicate groups can be joined together with other predicate groups. 66 | /// 67 | /// The grouping operator to use when joining the predicates (AND / OR). 68 | /// A list of predicates to group. 69 | /// An instance of IPredicateGroup. 70 | public static IPredicateGroup Group(GroupOperator op, params IPredicate[] predicate) 71 | { 72 | return new PredicateGroup 73 | { 74 | Operator = op, 75 | Predicates = predicate 76 | }; 77 | } 78 | 79 | /// 80 | /// Factory method that creates a new IExistsPredicate predicate. 81 | /// 82 | public static IExistsPredicate Exists(IPredicate predicate, bool not = false) 83 | where TSub : class 84 | { 85 | return new ExistsPredicate 86 | { 87 | Not = not, 88 | Predicate = predicate 89 | }; 90 | } 91 | 92 | /// 93 | /// Factory method that creates a new IBetweenPredicate predicate. 94 | /// 95 | public static IBetweenPredicate Between(Expression> expression, BetweenValues values, bool not = false) 96 | where T : class 97 | { 98 | PropertyInfo propertyInfo = ReflectionHelper.GetProperty(expression) as PropertyInfo; 99 | return new BetweenPredicate 100 | { 101 | Not = not, 102 | PropertyName = propertyInfo.Name, 103 | Value = values 104 | }; 105 | } 106 | 107 | /// 108 | /// Factory method that creates a new Sort which controls how the results will be sorted. 109 | /// 110 | public static ISort Sort(Expression> expression, bool ascending = true) 111 | { 112 | PropertyInfo propertyInfo = ReflectionHelper.GetProperty(expression) as PropertyInfo; 113 | return new Sort 114 | { 115 | PropertyName = propertyInfo.Name, 116 | Ascending = ascending 117 | }; 118 | } 119 | } 120 | } -------------------------------------------------------------------------------- /src/Galaxy.Libra.DapperExtensions/DBBuilder/MySQL/MySQLTableBuilder.cs: -------------------------------------------------------------------------------- 1 | using Dapper; 2 | using Galaxy.Libra.DapperExtensions.DBBuilder.MySQL.Convert; 3 | using Galaxy.Libra.DapperExtensions.Mapper; 4 | using System; 5 | using System.Collections.Generic; 6 | using System.Data; 7 | using System.Linq; 8 | using System.Reflection; 9 | using System.Text; 10 | 11 | namespace Galaxy.Libra.DapperExtensions.DBBuilder.MySQL 12 | { 13 | public class MySQLTableBuilder : ITableBuilder 14 | { 15 | protected IDbConnection curDbConnection = null; 16 | 17 | private Type t; 18 | private IClassMapper classMap; 19 | private List columnList = new List(); 20 | private string key; 21 | private string autoIncrementkey; 22 | private List uniquekey; 23 | 24 | protected IDBColumnConverter DBStringConverter; 25 | protected IDBColumnConverter DBIntConverter; 26 | protected IDBColumnConverter DBLongConverter; 27 | protected IDBColumnConverter DBDateTimeConverter; 28 | protected IDBColumnConverter DBEnumConverter; 29 | protected IDBColumnConverter DBBoolConverter; 30 | 31 | public MySQLTableBuilder(IDbConnection dbConnection) 32 | { 33 | curDbConnection = dbConnection; 34 | 35 | DBStringConverter = new MySqlStringConverter(); 36 | DBIntConverter = new MySQLIntConvert(); 37 | DBLongConverter = new MySQLLongConvert(); 38 | DBDateTimeConverter = new MySQLDateTimeConvert(); 39 | DBEnumConverter = new MySQLEnumConvert(); 40 | DBBoolConverter = new MySQLBoolConvert(); 41 | } 42 | 43 | public void CreateTable(Type t, IClassMapper classMap) 44 | { 45 | this.t = t; 46 | this.classMap = classMap; 47 | key = ""; 48 | autoIncrementkey = ""; 49 | uniquekey = new List(); 50 | columnList = new List(); 51 | 52 | string sql = BuildSQL(t); 53 | 54 | if (curDbConnection != null) 55 | { 56 | using (curDbConnection) 57 | { 58 | if (curDbConnection.State != ConnectionState.Open) 59 | curDbConnection.Open(); 60 | 61 | curDbConnection.Execute(sql); 62 | 63 | curDbConnection.Close(); 64 | } 65 | } 66 | } 67 | 68 | /// 69 | /// 获取表名称 70 | /// 71 | private string GetTableName() => string.IsNullOrEmpty(classMap.TableName) ? t.Name : classMap.TableName; 72 | 73 | protected void InitColumns() 74 | { 75 | PropertyInfo[] properties = t.GetProperties(); 76 | 77 | foreach (PropertyInfo pro in properties) 78 | { 79 | IPropertyMap propertyMap = classMap.Properties.SingleOrDefault(p => p.Name.Equals(pro.Name, StringComparison.InvariantCultureIgnoreCase)); 80 | 81 | if (!propertyMap.Ignored) 82 | InitColumn(pro, propertyMap); 83 | } 84 | } 85 | 86 | protected void InitColumn(PropertyInfo pro, IPropertyMap proMap) 87 | { 88 | string columnName = GetColumnName(pro, proMap); 89 | StringBuilder columnStrBuilder = new StringBuilder(columnName); 90 | Type proType = pro.PropertyType; 91 | string convertStr = null; 92 | 93 | if (proType == typeof(string) && DBStringConverter != null) 94 | convertStr = DBStringConverter.Convert(proMap); 95 | else if (proType == typeof(int) && DBIntConverter != null) 96 | convertStr = DBIntConverter.Convert(proMap); 97 | else if (proType == typeof(long) && DBLongConverter != null) 98 | convertStr = DBLongConverter.Convert(proMap); 99 | else if (proType == typeof(DateTime) && DBDateTimeConverter != null) 100 | convertStr = DBDateTimeConverter.Convert(proMap); 101 | else if (proType == typeof(bool) && DBBoolConverter != null) 102 | convertStr = DBBoolConverter.Convert(proMap); 103 | else 104 | convertStr = DBStringConverter.Convert(proMap); 105 | 106 | columnStrBuilder.Append($" {convertStr}"); 107 | 108 | if (proMap.IsRequired) 109 | columnStrBuilder.Append(" NOT NULL"); 110 | 111 | if (proMap.IsAutoIncrement) 112 | columnStrBuilder.Append(" AUTO_INCREMENT"); 113 | 114 | //if (proMap.) 115 | // uniquekey.Add(columnName); 116 | 117 | columnList.Add(columnStrBuilder.ToString()); 118 | 119 | if (proMap.KeyType != KeyType.NotAKey) 120 | key = $"PRIMARY KEY ({columnName})"; 121 | } 122 | 123 | /// 124 | /// 获取列名称 125 | /// 126 | protected string GetColumnName(PropertyInfo pro, IPropertyMap proMap) => string.IsNullOrEmpty(proMap.ColumnName) ? pro.Name : proMap.ColumnName; 127 | 128 | 129 | private string BuildSQL(Type t) 130 | { 131 | this.t = t; 132 | this.columnList = new List(); 133 | this.key = null; 134 | InitColumns(); 135 | 136 | if (!string.IsNullOrEmpty(key)) 137 | columnList.Add(key); 138 | 139 | if (!string.IsNullOrEmpty(autoIncrementkey)) 140 | columnList.Add(autoIncrementkey); 141 | 142 | if (uniquekey.Count > 0) 143 | { 144 | string uniquekeyStr = $"UNIQUE KEY {string.Join('_', uniquekey.ToArray())} ({string.Join(',', uniquekey.ToArray())})"; 145 | columnList.Add(uniquekeyStr); 146 | } 147 | 148 | StringBuilder SQLBuilder = new StringBuilder(); 149 | SQLBuilder.Append($"CREATE TABLE If Not Exists {GetTableName()} ( "); 150 | SQLBuilder.Append(string.Join(",", columnList.ToArray())); 151 | SQLBuilder.Append(" ) "); 152 | 153 | return SQLBuilder.ToString(); 154 | } 155 | } 156 | } 157 | -------------------------------------------------------------------------------- /src/Galaxy.Libra.DapperExtensions/Mapper/PropertyMap.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Reflection; 3 | 4 | namespace Galaxy.Libra.DapperExtensions.Mapper 5 | { 6 | /// 7 | /// Maps an entity property to its corresponding column in the database. 8 | /// 9 | public interface IPropertyMap 10 | { 11 | string Name { get; } 12 | string ColumnName { get; } 13 | bool Ignored { get; } 14 | bool IsReadOnly { get; } 15 | 16 | /// 17 | /// 字段长度 18 | /// 19 | int ColumnLength { get; } 20 | 21 | /// 22 | /// 是否允许为空 23 | /// 24 | bool IsRequired { get; } 25 | 26 | /// 27 | /// 是否自增字段 28 | /// 29 | bool IsAutoIncrement { get; } 30 | 31 | KeyType KeyType { get; } 32 | PropertyInfo PropertyInfo { get; } 33 | } 34 | 35 | /// 36 | /// Maps an entity property to its corresponding column in the database. 37 | /// 38 | public class PropertyMap : IPropertyMap 39 | { 40 | public PropertyMap(PropertyInfo propertyInfo) 41 | { 42 | PropertyInfo = propertyInfo; 43 | ColumnName = PropertyInfo.Name; 44 | } 45 | 46 | /// 47 | /// Gets the name of the property by using the specified propertyInfo. 48 | /// 49 | public string Name 50 | { 51 | get { return PropertyInfo.Name; } 52 | } 53 | 54 | /// 55 | /// Gets the column name for the current property. 56 | /// 57 | public string ColumnName { get; private set; } 58 | 59 | /// 60 | /// Gets the key type for the current property. 61 | /// 62 | public KeyType KeyType { get; private set; } 63 | 64 | /// 65 | /// Gets the ignore status of the current property. If ignored, the current property will not be included in queries. 66 | /// 67 | public bool Ignored { get; private set; } 68 | 69 | /// 70 | /// Gets the read-only status of the current property. If read-only, the current property will not be included in INSERT and UPDATE queries. 71 | /// 72 | public bool IsReadOnly { get; private set; } 73 | 74 | public bool IsRequired { get; private set; } 75 | 76 | public bool IsAutoIncrement { get; private set; } 77 | 78 | /// 79 | /// 设置字段长度 80 | /// 81 | public int ColumnLength { get; private set; } 82 | 83 | /// 84 | /// Gets the property info for the current property. 85 | /// 86 | public PropertyInfo PropertyInfo { get; private set; } 87 | 88 | /// 89 | /// 设置属性对应的数据表列名 90 | /// 91 | /// 数据表列名 92 | public PropertyMap Column(string columnName) 93 | { 94 | ColumnName = columnName; 95 | return this; 96 | } 97 | 98 | /// 99 | /// Fluently sets the key type of the property. 100 | /// 101 | /// The column name as it exists in the database. 102 | public PropertyMap Key(KeyType keyType) 103 | { 104 | if (Ignored) 105 | { 106 | throw new ArgumentException(string.Format("'{0}' is ignored and cannot be made a key field. ", Name)); 107 | } 108 | 109 | if (IsReadOnly) 110 | { 111 | throw new ArgumentException(string.Format("'{0}' is readonly and cannot be made a key field. ", Name)); 112 | } 113 | 114 | KeyType = keyType; 115 | return this; 116 | } 117 | 118 | /// 119 | /// 设置忽略该属性。 120 | /// 121 | public PropertyMap Ignore() 122 | { 123 | if (KeyType != KeyType.NotAKey) 124 | { 125 | throw new ArgumentException(string.Format("'{0}' is a key field and cannot be ignored.", Name)); 126 | } 127 | 128 | Ignored = true; 129 | return this; 130 | } 131 | 132 | public PropertyMap Required() 133 | { 134 | IsRequired = true; 135 | return this; 136 | } 137 | 138 | public PropertyMap AutoIncrement() 139 | { 140 | IsAutoIncrement = true; 141 | return this; 142 | } 143 | 144 | /// 145 | /// Fluently sets the read-only status of the property. 146 | /// 147 | public PropertyMap ReadOnly() 148 | { 149 | if (KeyType != KeyType.NotAKey) 150 | { 151 | throw new ArgumentException(string.Format("'{0}' is a key field and cannot be marked readonly.", Name)); 152 | } 153 | 154 | IsReadOnly = true; 155 | return this; 156 | } 157 | 158 | /// 159 | /// 设置字段长度 160 | /// 161 | public PropertyMap Length(int length) 162 | { 163 | ColumnLength = length; 164 | return this; 165 | } 166 | } 167 | 168 | /// 169 | /// Used by ClassMapper to determine which entity property represents the key. 170 | /// 171 | public enum KeyType 172 | { 173 | /// 174 | /// The property is not a key and is not automatically managed. 175 | /// 176 | NotAKey, 177 | 178 | /// 179 | /// The property is an integery-based identity generated from the database. 180 | /// 181 | Identity, 182 | 183 | /// 184 | /// The property is a Guid identity which is automatically managed. 185 | /// 186 | Guid, 187 | 188 | /// 189 | /// The property is a key that is not automatically managed. 190 | /// 191 | Assigned 192 | } 193 | } -------------------------------------------------------------------------------- /src/Galaxy.Libra.DapperExtensions/Mapper/ClassMapper.cs: -------------------------------------------------------------------------------- 1 | using System.Numerics; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.Globalization; 5 | using System.Linq; 6 | using System.Linq.Expressions; 7 | using System.Reflection; 8 | 9 | namespace Galaxy.Libra.DapperExtensions.Mapper 10 | { 11 | public interface IClassMapper 12 | { 13 | string SchemaName { get; } 14 | string TableName { get; } 15 | IList Properties { get; } 16 | Type EntityType { get; } 17 | } 18 | 19 | public interface IClassMapper : IClassMapper where T : class 20 | { 21 | } 22 | 23 | /// 24 | /// Maps an entity to a table through a collection of property maps. 25 | /// 26 | public class ClassMapper : IClassMapper where T : class 27 | { 28 | /// 29 | /// Gets or sets the schema to use when referring to the corresponding table name in the database. 30 | /// 31 | public string SchemaName { get; protected set; } 32 | 33 | /// 34 | /// Gets or sets the table to use in the database. 35 | /// 36 | public string TableName { get; protected set; } 37 | 38 | /// 39 | /// A collection of properties that will map to columns in the database table. 40 | /// 41 | public IList Properties { get; private set; } 42 | 43 | public Type EntityType 44 | { 45 | get { return typeof(T); } 46 | } 47 | 48 | public ClassMapper() 49 | { 50 | PropertyTypeKeyTypeMapping = new Dictionary 51 | { 52 | { typeof(byte), KeyType.Identity }, { typeof(byte?), KeyType.Identity }, 53 | { typeof(sbyte), KeyType.Identity }, { typeof(sbyte?), KeyType.Identity }, 54 | { typeof(short), KeyType.Identity }, { typeof(short?), KeyType.Identity }, 55 | { typeof(ushort), KeyType.Identity }, { typeof(ushort?), KeyType.Identity }, 56 | { typeof(int), KeyType.Identity }, { typeof(int?), KeyType.Identity }, 57 | { typeof(uint), KeyType.Identity}, { typeof(uint?), KeyType.Identity }, 58 | { typeof(long), KeyType.Identity }, { typeof(long?), KeyType.Identity }, 59 | { typeof(ulong), KeyType.Identity }, { typeof(ulong?), KeyType.Identity }, 60 | { typeof(BigInteger), KeyType.Identity }, { typeof(BigInteger?), KeyType.Identity }, 61 | { typeof(Guid), KeyType.Guid }, { typeof(Guid?), KeyType.Guid }, 62 | }; 63 | 64 | Properties = new List(); 65 | Table(typeof(T).Name); 66 | } 67 | 68 | protected Dictionary PropertyTypeKeyTypeMapping { get; private set; } 69 | 70 | public virtual void Schema(string schemaName) 71 | { 72 | SchemaName = schemaName; 73 | } 74 | 75 | public virtual void Table(string tableName) 76 | { 77 | TableName = tableName; 78 | } 79 | 80 | protected virtual void AutoMap() 81 | { 82 | AutoMap(null); 83 | } 84 | 85 | protected virtual void AutoMap(Func canMap) 86 | { 87 | Type type = typeof(T); 88 | bool hasDefinedKey = Properties.Any(p => p.KeyType != KeyType.NotAKey); 89 | PropertyMap keyMap = null; 90 | foreach (var propertyInfo in type.GetProperties()) 91 | { 92 | if (Properties.Any(p => p.Name.Equals(propertyInfo.Name, StringComparison.InvariantCultureIgnoreCase))) 93 | { 94 | continue; 95 | } 96 | 97 | if ((canMap != null && !canMap(type, propertyInfo))) 98 | { 99 | continue; 100 | } 101 | 102 | PropertyMap map = Map(propertyInfo); 103 | if (!hasDefinedKey) 104 | { 105 | if (string.Equals(map.PropertyInfo.Name, "id", StringComparison.InvariantCultureIgnoreCase)) 106 | { 107 | keyMap = map; 108 | } 109 | 110 | if (keyMap == null && map.PropertyInfo.Name.EndsWith("id", true, CultureInfo.InvariantCulture)) 111 | { 112 | keyMap = map; 113 | } 114 | } 115 | } 116 | 117 | if (keyMap != null) 118 | { 119 | keyMap.Key(PropertyTypeKeyTypeMapping.ContainsKey(keyMap.PropertyInfo.PropertyType) 120 | ? PropertyTypeKeyTypeMapping[keyMap.PropertyInfo.PropertyType] 121 | : KeyType.Assigned); 122 | } 123 | } 124 | 125 | /// 126 | /// Fluently, maps an entity property to a column 127 | /// 128 | protected PropertyMap Map(Expression> expression) 129 | { 130 | PropertyInfo propertyInfo = ReflectionHelper.GetProperty(expression) as PropertyInfo; 131 | return Map(propertyInfo); 132 | } 133 | 134 | /// 135 | /// Fluently, maps an entity property to a column 136 | /// 137 | protected PropertyMap Map(PropertyInfo propertyInfo) 138 | { 139 | PropertyMap result = new PropertyMap(propertyInfo); 140 | this.GuardForDuplicatePropertyMap(result); 141 | Properties.Add(result); 142 | return result; 143 | } 144 | 145 | private void GuardForDuplicatePropertyMap(PropertyMap result) 146 | { 147 | if (Properties.Any(p => p.Name.Equals(result.Name))) 148 | { 149 | throw new ArgumentException(string.Format("Duplicate mapping for property {0} detected.",result.Name)); 150 | } 151 | } 152 | } 153 | } -------------------------------------------------------------------------------- /src/Galaxy.Libra.DapperExtensions/PredicateConver/ExpressionPredicateConvert.cs: -------------------------------------------------------------------------------- 1 | using Galaxy.Libra.DapperExtensions.Predicate; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.Linq; 5 | using System.Linq.Expressions; 6 | 7 | namespace Galaxy.Libra.DapperExtensions.PredicateConver 8 | { 9 | public class ExpressionPredicateConvert 10 | { 11 | /// 12 | /// 将表达式转换为Predicate 13 | /// 14 | public static IPredicate GetExpressionPredicate(Expression> expression) where T : class 15 | { 16 | Expression expr = expression.Body; 17 | return ConvertToPredicate(expr); 18 | } 19 | 20 | private static IPredicate ConvertToPredicate(Expression expr) where T : class 21 | { 22 | if (expr.NodeType == ExpressionType.OrElse || expr.NodeType == ExpressionType.AndAlso) 23 | { 24 | BinaryExpression binExpr = expr as BinaryExpression; 25 | IList predList = new List { ConvertToPredicate(binExpr.Left), ConvertToPredicate(binExpr.Right) }; 26 | GroupOperator op = expr.NodeType == ExpressionType.OrElse ? GroupOperator.Or : GroupOperator.And; 27 | return Predicates.Group(op, predList.ToArray()); 28 | } 29 | else if (expr.NodeType == ExpressionType.Equal || expr.NodeType == ExpressionType.NotEqual 30 | || expr.NodeType == ExpressionType.GreaterThan || expr.NodeType == ExpressionType.GreaterThanOrEqual 31 | || expr.NodeType == ExpressionType.LessThan || expr.NodeType == ExpressionType.LessThanOrEqual) 32 | { 33 | return ConvertBaseExpression(expr as BinaryExpression); 34 | } 35 | else if (expr.NodeType == ExpressionType.Call) 36 | { 37 | return ConverCallExpression(expr); 38 | } 39 | else if (expr.NodeType == ExpressionType.Not) 40 | { 41 | return ConverNotInExpression(expr); 42 | } 43 | 44 | return null; 45 | } 46 | 47 | private static IPredicate ConvertBaseExpression(Expression expr) where T : class 48 | { 49 | BinaryExpression binExpr = expr as BinaryExpression; 50 | MemberExpression menLeftExpr = binExpr.Left as MemberExpression; 51 | ConstantExpression conRightExpr = binExpr.Right as ConstantExpression; 52 | 53 | if (menLeftExpr != null) 54 | { 55 | Operator op = Operator.Eq; 56 | bool not = false; 57 | 58 | switch (binExpr.NodeType) 59 | { 60 | case ExpressionType.Equal: 61 | op = Operator.Eq; 62 | break; 63 | case ExpressionType.NotEqual: 64 | op = Operator.Eq; 65 | not = true; 66 | break; 67 | case ExpressionType.LessThan: 68 | op = Operator.Lt; 69 | break; 70 | case ExpressionType.GreaterThan: 71 | op = Operator.Gt; 72 | break; 73 | case ExpressionType.GreaterThanOrEqual: 74 | op = Operator.Ge; 75 | break; 76 | case ExpressionType.LessThanOrEqual: 77 | op = Operator.Le; 78 | break; 79 | default: 80 | throw new Exception($"未实现该操作符逻辑{binExpr.NodeType}"); 81 | } 82 | 83 | return new FieldPredicate 84 | { 85 | PropertyName = menLeftExpr.Member.Name, 86 | Operator = op, 87 | Not = not, 88 | Value = GetExpressionValue(binExpr.Right) 89 | }; 90 | } 91 | 92 | return null; 93 | } 94 | 95 | private static object GetExpressionValue(Expression expr) 96 | { 97 | ConstantExpression con = expr as ConstantExpression; 98 | if (con != null) 99 | return con.Value; 100 | 101 | MemberExpression mem = expr as MemberExpression; 102 | if (mem != null) 103 | { 104 | if (mem.Type == typeof(int)) 105 | return Expression.Lambda>(mem).Compile()(); 106 | else if (mem.Type == typeof(double)) 107 | return Expression.Lambda>(mem).Compile()(); 108 | else if (mem.Type == typeof(float)) 109 | return Expression.Lambda>(mem).Compile()(); 110 | else if (mem.Type == typeof(decimal)) 111 | return Expression.Lambda>(mem).Compile()(); 112 | else if (mem.Type == typeof(long)) 113 | return Expression.Lambda>(mem).Compile()(); 114 | else if (mem.Type == typeof(string)) 115 | return Expression.Lambda>(mem).Compile()(); 116 | else 117 | return Expression.Lambda>(mem).Compile()(); 118 | } 119 | 120 | return null; 121 | } 122 | 123 | private static IPredicate ConverCallExpression(Expression expr) where T : class 124 | { 125 | MethodCallExpression methExpr = expr as MethodCallExpression; 126 | MemberExpression menExpr = methExpr.Object as MemberExpression; 127 | 128 | //判断是否是列表,如果是列表则进行in条件构建 129 | if (menExpr.Type.IsGenericType == true || menExpr.Type.IsArray == true) 130 | { 131 | string propertyName = (methExpr.Arguments[0] as MemberExpression).Member.Name; 132 | object value = Expression.Lambda>(menExpr).Compile()(); 133 | 134 | return new FieldPredicate 135 | { 136 | PropertyName = propertyName, 137 | Operator = Operator.Eq, 138 | Value = value 139 | }; 140 | } 141 | else 142 | { 143 | string propertyName = menExpr.Member.Name; 144 | string methName = methExpr.Method.Name; 145 | string paramStr = (methExpr.Arguments[0] as ConstantExpression).Value.ToString(); 146 | 147 | switch (methName) 148 | { 149 | case "Contains": 150 | paramStr = $"%{paramStr}%"; 151 | break; 152 | case "StartsWith": 153 | paramStr = $"{paramStr}%"; 154 | break; 155 | case "EndsWith": 156 | paramStr = $"%{paramStr}"; 157 | break; 158 | default: 159 | throw new Exception($"未能解析该方法{methName}"); 160 | } 161 | 162 | return new FieldPredicate 163 | { 164 | PropertyName = propertyName, 165 | Operator = Operator.Like, 166 | Value = paramStr 167 | }; 168 | } 169 | } 170 | 171 | private static IPredicate ConverNotInExpression(Expression expr) where T : class 172 | { 173 | UnaryExpression tempExpr = expr as UnaryExpression; 174 | IPredicate predicate = ConverCallExpression(tempExpr.Operand); 175 | (predicate as FieldPredicate).Not = true; 176 | return predicate; 177 | } 178 | } 179 | } 180 | -------------------------------------------------------------------------------- /src/Galaxy.Libra.DapperExtensions/Sql/SqlGenerator.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using Galaxy.Libra.DapperExtensions.Mapper; 6 | using Galaxy.Libra.DapperExtensions.Predicate; 7 | 8 | namespace Galaxy.Libra.DapperExtensions.Sql 9 | { 10 | public interface ISqlGenerator 11 | { 12 | IDapperExtensionsConfiguration Configuration { get; } 13 | 14 | string Select(IClassMapper classMap, IPredicate predicate, IList sort, IDictionary parameters); 15 | string SelectPaged(IClassMapper classMap, IPredicate predicate, IList sort, int page, int resultsPerPage, IDictionary parameters); 16 | string SelectSet(IClassMapper classMap, IPredicate predicate, IList sort, int firstResult, int maxResults, IDictionary parameters); 17 | string Count(IClassMapper classMap, IPredicate predicate, IDictionary parameters); 18 | 19 | string Insert(IClassMapper classMap); 20 | string Update(IClassMapper classMap, IPredicate predicate, IDictionary parameters); 21 | string Delete(IClassMapper classMap, IPredicate predicate, IDictionary parameters); 22 | 23 | string IdentitySql(IClassMapper classMap); 24 | string GetTableName(IClassMapper map); 25 | string GetColumnName(IClassMapper map, IPropertyMap property, bool includeAlias); 26 | string GetColumnName(IClassMapper map, string propertyName, bool includeAlias); 27 | bool SupportsMultipleStatements(); 28 | } 29 | 30 | public class SqlGeneratorImpl : ISqlGenerator 31 | { 32 | public SqlGeneratorImpl(IDapperExtensionsConfiguration configuration) 33 | { 34 | Configuration = configuration; 35 | } 36 | 37 | public IDapperExtensionsConfiguration Configuration { get; private set; } 38 | 39 | public virtual string Select(IClassMapper classMap, IPredicate predicate, IList sort, IDictionary parameters) 40 | { 41 | if (parameters == null) 42 | { 43 | throw new ArgumentNullException("Parameters"); 44 | } 45 | 46 | StringBuilder sql = new StringBuilder(string.Format("SELECT {0} FROM {1}", 47 | BuildSelectColumns(classMap), 48 | GetTableName(classMap))); 49 | if (predicate != null) 50 | { 51 | sql.Append(" WHERE ") 52 | .Append(predicate.GetSql(this, parameters)); 53 | } 54 | 55 | if (sort != null && sort.Any()) 56 | { 57 | sql.Append(" ORDER BY ") 58 | .Append(sort.Select(s => GetColumnName(classMap, s.PropertyName, false) + (s.Ascending ? " ASC" : " DESC")).AppendStrings()); 59 | } 60 | 61 | return sql.ToString(); 62 | } 63 | 64 | public virtual string SelectPaged(IClassMapper classMap, IPredicate predicate, IList sort, int page, int resultsPerPage, IDictionary parameters) 65 | { 66 | if (sort == null || !sort.Any()) 67 | { 68 | throw new ArgumentNullException("Sort", "Sort cannot be null or empty."); 69 | } 70 | 71 | if (parameters == null) 72 | { 73 | throw new ArgumentNullException("Parameters"); 74 | } 75 | 76 | StringBuilder innerSql = new StringBuilder(string.Format("SELECT {0} FROM {1}", 77 | BuildSelectColumns(classMap), 78 | GetTableName(classMap))); 79 | if (predicate != null) 80 | { 81 | innerSql.Append(" WHERE ") 82 | .Append(predicate.GetSql(this, parameters)); 83 | } 84 | 85 | string orderBy = sort.Select(s => GetColumnName(classMap, s.PropertyName, false) + (s.Ascending ? " ASC" : " DESC")).AppendStrings(); 86 | innerSql.Append(" ORDER BY " + orderBy); 87 | 88 | string sql = Configuration.Dialect.GetPagingSql(innerSql.ToString(), page, resultsPerPage, parameters); 89 | return sql; 90 | } 91 | 92 | public virtual string SelectSet(IClassMapper classMap, IPredicate predicate, IList sort, int firstResult, int maxResults, IDictionary parameters) 93 | { 94 | if (sort == null || !sort.Any()) 95 | { 96 | throw new ArgumentNullException("Sort", "Sort cannot be null or empty."); 97 | } 98 | 99 | if (parameters == null) 100 | { 101 | throw new ArgumentNullException("Parameters"); 102 | } 103 | 104 | StringBuilder innerSql = new StringBuilder(string.Format("SELECT {0} FROM {1}", 105 | BuildSelectColumns(classMap), 106 | GetTableName(classMap))); 107 | if (predicate != null) 108 | { 109 | innerSql.Append(" WHERE ") 110 | .Append(predicate.GetSql(this, parameters)); 111 | } 112 | 113 | string orderBy = sort.Select(s => GetColumnName(classMap, s.PropertyName, false) + (s.Ascending ? " ASC" : " DESC")).AppendStrings(); 114 | innerSql.Append(" ORDER BY " + orderBy); 115 | 116 | string sql = Configuration.Dialect.GetSetSql(innerSql.ToString(), firstResult, maxResults, parameters); 117 | return sql; 118 | } 119 | 120 | 121 | public virtual string Count(IClassMapper classMap, IPredicate predicate, IDictionary parameters) 122 | { 123 | if (parameters == null) 124 | { 125 | throw new ArgumentNullException("Parameters"); 126 | } 127 | 128 | StringBuilder sql = new StringBuilder(string.Format("SELECT COUNT(*) AS {0}Total{1} FROM {2}", 129 | Configuration.Dialect.OpenQuote, 130 | Configuration.Dialect.CloseQuote, 131 | GetTableName(classMap))); 132 | if (predicate != null) 133 | { 134 | sql.Append(" WHERE ") 135 | .Append(predicate.GetSql(this, parameters)); 136 | } 137 | 138 | return sql.ToString(); 139 | } 140 | 141 | public virtual string Insert(IClassMapper classMap) 142 | { 143 | var columns = classMap.Properties.Where(p => !(p.Ignored || p.IsReadOnly || p.KeyType == KeyType.Identity)); 144 | if (!columns.Any()) 145 | { 146 | throw new ArgumentException("No columns were mapped."); 147 | } 148 | 149 | var columnNames = columns.Select(p => GetColumnName(classMap, p, false)); 150 | var parameters = columns.Select(p => Configuration.Dialect.ParameterPrefix + p.Name); 151 | 152 | string sql = string.Format("INSERT INTO {0} ({1}) VALUES ({2})", 153 | GetTableName(classMap), 154 | columnNames.AppendStrings(), 155 | parameters.AppendStrings()); 156 | 157 | return sql; 158 | } 159 | 160 | public virtual string Update(IClassMapper classMap, IPredicate predicate, IDictionary parameters) 161 | { 162 | if (predicate == null) 163 | { 164 | throw new ArgumentNullException("Predicate"); 165 | } 166 | 167 | if (parameters == null) 168 | { 169 | throw new ArgumentNullException("Parameters"); 170 | } 171 | 172 | var columns = classMap.Properties.Where(p => !(p.Ignored || p.IsReadOnly || p.KeyType == KeyType.Identity)); 173 | if (!columns.Any()) 174 | { 175 | throw new ArgumentException("No columns were mapped."); 176 | } 177 | 178 | var setSql = 179 | columns.Select( 180 | p => 181 | string.Format( 182 | "{0} = {1}{2}", GetColumnName(classMap, p, false), Configuration.Dialect.ParameterPrefix, p.Name)); 183 | 184 | return string.Format("UPDATE {0} SET {1} WHERE {2}", 185 | GetTableName(classMap), 186 | setSql.AppendStrings(), 187 | predicate.GetSql(this, parameters)); 188 | } 189 | 190 | public virtual string Delete(IClassMapper classMap, IPredicate predicate, IDictionary parameters) 191 | { 192 | if (predicate == null) 193 | { 194 | throw new ArgumentNullException("Predicate"); 195 | } 196 | 197 | if (parameters == null) 198 | { 199 | throw new ArgumentNullException("Parameters"); 200 | } 201 | 202 | StringBuilder sql = new StringBuilder(string.Format("DELETE FROM {0}", GetTableName(classMap))); 203 | sql.Append(" WHERE ").Append(predicate.GetSql(this, parameters)); 204 | return sql.ToString(); 205 | } 206 | 207 | public virtual string IdentitySql(IClassMapper classMap) 208 | { 209 | return Configuration.Dialect.GetIdentitySql(GetTableName(classMap)); 210 | } 211 | 212 | public virtual string GetTableName(IClassMapper map) 213 | { 214 | return Configuration.Dialect.GetTableName(map.SchemaName, map.TableName, null); 215 | } 216 | 217 | public virtual string GetColumnName(IClassMapper map, IPropertyMap property, bool includeAlias) 218 | { 219 | string alias = null; 220 | if (property.ColumnName != property.Name && includeAlias) 221 | { 222 | alias = property.Name; 223 | } 224 | 225 | return Configuration.Dialect.GetColumnName(GetTableName(map), property.ColumnName, alias); 226 | } 227 | 228 | public virtual string GetColumnName(IClassMapper map, string propertyName, bool includeAlias) 229 | { 230 | IPropertyMap propertyMap = map.Properties.SingleOrDefault(p => p.Name.Equals(propertyName, StringComparison.InvariantCultureIgnoreCase)); 231 | if (propertyMap == null) 232 | { 233 | throw new ArgumentException(string.Format("Could not find '{0}' in Mapping.", propertyName)); 234 | } 235 | 236 | return GetColumnName(map, propertyMap, includeAlias); 237 | } 238 | 239 | public virtual bool SupportsMultipleStatements() 240 | { 241 | return Configuration.Dialect.SupportsMultipleStatements; 242 | } 243 | 244 | public virtual string BuildSelectColumns(IClassMapper classMap) 245 | { 246 | var columns = classMap.Properties 247 | .Where(p => !p.Ignored) 248 | .Select(p => GetColumnName(classMap, p, true)); 249 | return columns.AppendStrings(); 250 | } 251 | } 252 | } -------------------------------------------------------------------------------- /src/Galaxy.Libra.DapperExtensions/Database.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Data; 4 | using System.Linq; 5 | using System.Text; 6 | using Galaxy.Libra.DapperExtensions.Mapper; 7 | using Galaxy.Libra.DapperExtensions.Sql; 8 | using Galaxy.Libra.DapperExtensions.Predicate; 9 | using Galaxy.Libra.DapperExtensions.DapperImpl; 10 | 11 | namespace Galaxy.Libra.DapperExtensions 12 | { 13 | public interface IDatabase : IDisposable 14 | { 15 | bool HasActiveTransaction { get; } 16 | IDbConnection Connection { get; } 17 | void BeginTransaction(IsolationLevel isolationLevel = IsolationLevel.ReadCommitted); 18 | void Commit(); 19 | void Rollback(); 20 | void RunInTransaction(Action action); 21 | T RunInTransaction(Func func); 22 | T Get(dynamic id, IDbTransaction transaction, int? commandTimeout = null) where T : class; 23 | T Get(dynamic id, int? commandTimeout = null) where T : class; 24 | void Insert(IEnumerable entities, IDbTransaction transaction, int? commandTimeout = null) where T : class; 25 | void Insert(IEnumerable entities, int? commandTimeout = null) where T : class; 26 | dynamic Insert(T entity, IDbTransaction transaction, int? commandTimeout = null) where T : class; 27 | dynamic Insert(T entity, int? commandTimeout = null) where T : class; 28 | bool Update(T entity, IDbTransaction transaction, int? commandTimeout = null) where T : class; 29 | bool Update(T entity, int? commandTimeout = null) where T : class; 30 | bool Delete(T entity, IDbTransaction transaction, int? commandTimeout = null) where T : class; 31 | bool Delete(T entity, int? commandTimeout = null) where T : class; 32 | bool DeleteWhere(object predicate, IDbTransaction transaction, int? commandTimeout = null) where T : class; 33 | bool DeleteWhere(object predicate, int? commandTimeout = null) where T : class; 34 | IEnumerable GetList(object predicate, IList sort, IDbTransaction transaction, int? commandTimeout = null, bool buffered = true) where T : class; 35 | IEnumerable GetList(object predicate = null, IList sort = null, int? commandTimeout = null, bool buffered = true) where T : class; 36 | IEnumerable GetPage(object predicate, IList sort, int page, int resultsPerPage, IDbTransaction transaction, int? commandTimeout = null, bool buffered = true) where T : class; 37 | IEnumerable GetPage(object predicate, IList sort, int page, int resultsPerPage, int? commandTimeout = null, bool buffered = true) where T : class; 38 | IEnumerable GetSet(object predicate, IList sort, int firstResult, int maxResults, IDbTransaction transaction, int? commandTimeout, bool buffered) where T : class; 39 | IEnumerable GetSet(object predicate, IList sort, int firstResult, int maxResults, int? commandTimeout, bool buffered) where T : class; 40 | int Count(object predicate, IDbTransaction transaction, int? commandTimeout = null) where T : class; 41 | int Count(object predicate, int? commandTimeout = null) where T : class; 42 | IMultipleResultReader GetMultiple(GetMultiplePredicate predicate, IDbTransaction transaction, int? commandTimeout = null); 43 | IMultipleResultReader GetMultiple(GetMultiplePredicate predicate, int? commandTimeout = null); 44 | void ClearCache(); 45 | Guid GetNextGuid(); 46 | IClassMapper GetMap() where T : class; 47 | } 48 | 49 | public class Database : IDatabase 50 | { 51 | private readonly IDapperImplementor _dapper; 52 | 53 | private IDbTransaction _transaction; 54 | 55 | public Database(IDbConnection connection, ISqlGenerator sqlGenerator) 56 | { 57 | _dapper = new DapperImplementor(sqlGenerator); 58 | Connection = connection; 59 | 60 | if (Connection.State != ConnectionState.Open) 61 | { 62 | Connection.Open(); 63 | } 64 | } 65 | 66 | public bool HasActiveTransaction 67 | { 68 | get 69 | { 70 | return _transaction != null; 71 | } 72 | } 73 | 74 | public IDbConnection Connection { get; private set; } 75 | 76 | public void Dispose() 77 | { 78 | if (Connection.State != ConnectionState.Closed) 79 | { 80 | if (_transaction != null) 81 | { 82 | _transaction.Rollback(); 83 | } 84 | 85 | Connection.Close(); 86 | } 87 | } 88 | 89 | public void BeginTransaction(IsolationLevel isolationLevel = IsolationLevel.ReadCommitted) 90 | { 91 | _transaction = Connection.BeginTransaction(isolationLevel); 92 | } 93 | 94 | public void Commit() 95 | { 96 | _transaction.Commit(); 97 | _transaction = null; 98 | } 99 | 100 | public void Rollback() 101 | { 102 | _transaction.Rollback(); 103 | _transaction = null; 104 | } 105 | 106 | public void RunInTransaction(Action action) 107 | { 108 | BeginTransaction(); 109 | try 110 | { 111 | action(); 112 | Commit(); 113 | } 114 | catch (Exception ex) 115 | { 116 | if (HasActiveTransaction) 117 | { 118 | Rollback(); 119 | } 120 | 121 | throw ex; 122 | } 123 | } 124 | 125 | public T RunInTransaction(Func func) 126 | { 127 | BeginTransaction(); 128 | try 129 | { 130 | T result = func(); 131 | Commit(); 132 | return result; 133 | } 134 | catch (Exception ex) 135 | { 136 | if (HasActiveTransaction) 137 | { 138 | Rollback(); 139 | } 140 | 141 | throw ex; 142 | } 143 | } 144 | 145 | public T Get(dynamic id, IDbTransaction transaction, int? commandTimeout) where T : class 146 | { 147 | return (T)_dapper.Get(Connection, id, transaction, commandTimeout); 148 | } 149 | 150 | public T Get(dynamic id, int? commandTimeout) where T : class 151 | { 152 | return (T)_dapper.Get(Connection, id, _transaction, commandTimeout); 153 | } 154 | 155 | public void Insert(IEnumerable entities, IDbTransaction transaction, int? commandTimeout) where T : class 156 | { 157 | _dapper.Insert(Connection, entities, transaction, commandTimeout); 158 | } 159 | 160 | public void Insert(IEnumerable entities, int? commandTimeout) where T : class 161 | { 162 | _dapper.Insert(Connection, entities, _transaction, commandTimeout); 163 | } 164 | 165 | public dynamic Insert(T entity, IDbTransaction transaction, int? commandTimeout) where T : class 166 | { 167 | return _dapper.Insert(Connection, entity, transaction, commandTimeout); 168 | } 169 | 170 | public dynamic Insert(T entity, int? commandTimeout) where T : class 171 | { 172 | return _dapper.Insert(Connection, entity, _transaction, commandTimeout); 173 | } 174 | 175 | public bool Update(T entity, IDbTransaction transaction, int? commandTimeout) where T : class 176 | { 177 | return _dapper.Update(Connection, entity, transaction, commandTimeout); 178 | } 179 | 180 | public bool Update(T entity, int? commandTimeout) where T : class 181 | { 182 | return _dapper.Update(Connection, entity, _transaction, commandTimeout); 183 | } 184 | 185 | public bool Delete(T entity, IDbTransaction transaction, int? commandTimeout) where T : class 186 | { 187 | return _dapper.Delete(Connection, entity, transaction, commandTimeout); 188 | } 189 | 190 | public bool Delete(T entity, int? commandTimeout) where T : class 191 | { 192 | return _dapper.Delete(Connection, entity, _transaction, commandTimeout); 193 | } 194 | 195 | public bool DeleteWhere(object predicate, IDbTransaction transaction, int? commandTimeout) where T : class 196 | { 197 | return _dapper.Delete(Connection, predicate, transaction, commandTimeout); 198 | } 199 | 200 | public bool DeleteWhere(object predicate, int? commandTimeout) where T : class 201 | { 202 | return _dapper.Delete(Connection, predicate, _transaction, commandTimeout); 203 | } 204 | 205 | public IEnumerable GetList(object predicate, IList sort, IDbTransaction transaction, int? commandTimeout, bool buffered) where T : class 206 | { 207 | return _dapper.GetList(Connection, predicate, sort, transaction, commandTimeout, buffered); 208 | } 209 | 210 | public IEnumerable GetList(object predicate, IList sort, int? commandTimeout, bool buffered) where T : class 211 | { 212 | return _dapper.GetList(Connection, predicate, sort, _transaction, commandTimeout, buffered); 213 | } 214 | 215 | public IEnumerable GetPage(object predicate, IList sort, int page, int resultsPerPage, IDbTransaction transaction, int? commandTimeout, bool buffered) where T : class 216 | { 217 | return _dapper.GetPage(Connection, predicate, sort, page, resultsPerPage, transaction, commandTimeout, buffered); 218 | } 219 | 220 | public IEnumerable GetPage(object predicate, IList sort, int page, int resultsPerPage, int? commandTimeout, bool buffered) where T : class 221 | { 222 | return _dapper.GetPage(Connection, predicate, sort, page, resultsPerPage, _transaction, commandTimeout, buffered); 223 | } 224 | 225 | public IEnumerable GetSet(object predicate, IList sort, int firstResult, int maxResults, IDbTransaction transaction, int? commandTimeout, bool buffered) where T : class 226 | { 227 | return _dapper.GetSet(Connection, predicate, sort, firstResult, maxResults, transaction, commandTimeout, buffered); 228 | } 229 | 230 | public IEnumerable GetSet(object predicate, IList sort, int firstResult, int maxResults, int? commandTimeout, bool buffered) where T : class 231 | { 232 | return _dapper.GetSet(Connection, predicate, sort, firstResult, maxResults, _transaction, commandTimeout, buffered); 233 | } 234 | 235 | public int Count(object predicate, IDbTransaction transaction, int? commandTimeout) where T : class 236 | { 237 | return _dapper.Count(Connection, predicate, transaction, commandTimeout); 238 | } 239 | 240 | public int Count(object predicate, int? commandTimeout) where T : class 241 | { 242 | return _dapper.Count(Connection, predicate, _transaction, commandTimeout); 243 | } 244 | 245 | public IMultipleResultReader GetMultiple(GetMultiplePredicate predicate, IDbTransaction transaction, int? commandTimeout) 246 | { 247 | return _dapper.GetMultiple(Connection, predicate, transaction, commandTimeout); 248 | } 249 | 250 | public IMultipleResultReader GetMultiple(GetMultiplePredicate predicate, int? commandTimeout) 251 | { 252 | return _dapper.GetMultiple(Connection, predicate, _transaction, commandTimeout); 253 | } 254 | 255 | public void ClearCache() 256 | { 257 | _dapper.SqlGenerator.Configuration.ClearCache(); 258 | } 259 | 260 | public Guid GetNextGuid() 261 | { 262 | return _dapper.SqlGenerator.Configuration.GetNextGuid(); 263 | } 264 | 265 | public IClassMapper GetMap() where T : class 266 | { 267 | return _dapper.SqlGenerator.Configuration.GetMap(); 268 | } 269 | } 270 | } -------------------------------------------------------------------------------- /src/Galaxy.Libra.DapperExtensions/DapperExtensions.cs: -------------------------------------------------------------------------------- 1 | using Galaxy.Libra.DapperExtensions.DapperImpl; 2 | using Galaxy.Libra.DapperExtensions.Mapper; 3 | using Galaxy.Libra.DapperExtensions.Predicate; 4 | using Galaxy.Libra.DapperExtensions.Sql; 5 | using System; 6 | using System.Collections.Generic; 7 | using System.Data; 8 | using System.Linq.Expressions; 9 | using System.Reflection; 10 | 11 | namespace Galaxy.Libra.DapperExtensions 12 | { 13 | public static class DapperExtensions 14 | { 15 | private readonly static object _lock = new object(); 16 | 17 | private static Func _instanceFactory; 18 | private static IDapperImplementor _instance; 19 | private static IDapperExtensionsConfiguration _configuration; 20 | 21 | /// 22 | /// Gets or sets the default class mapper to use when generating class maps. If not specified, AutoClassMapper is used. 23 | /// DapperExtensions.Configure(Type, IList, ISqlDialect) can be used instead to set all values at once 24 | /// 25 | public static Type DefaultMapper 26 | { 27 | get 28 | { 29 | return _configuration.DefaultMapper; 30 | } 31 | 32 | set 33 | { 34 | Configure(value, _configuration.MappingAssemblies, _configuration.Dialect); 35 | } 36 | } 37 | 38 | /// 39 | /// Gets or sets the type of sql to be generated. 40 | /// DapperExtensions.Configure(Type, IList, ISqlDialect) can be used instead to set all values at once 41 | /// 42 | public static ISqlDialect SqlDialect 43 | { 44 | get 45 | { 46 | return _configuration.Dialect; 47 | } 48 | 49 | set 50 | { 51 | Configure(_configuration.DefaultMapper, _configuration.MappingAssemblies, value); 52 | } 53 | } 54 | 55 | /// 56 | /// Get or sets the Dapper Extensions Implementation Factory. 57 | /// 58 | public static Func InstanceFactory 59 | { 60 | get 61 | { 62 | if (_instanceFactory == null) 63 | { 64 | _instanceFactory = config => new DapperImplementor(new SqlGeneratorImpl(config)); 65 | } 66 | 67 | return _instanceFactory; 68 | } 69 | set 70 | { 71 | _instanceFactory = value; 72 | Configure(_configuration.DefaultMapper, _configuration.MappingAssemblies, _configuration.Dialect); 73 | } 74 | } 75 | 76 | /// 77 | /// Gets the Dapper Extensions Implementation 78 | /// 79 | private static IDapperImplementor Instance 80 | { 81 | get 82 | { 83 | if (_instance == null) 84 | { 85 | lock (_lock) 86 | { 87 | if (_instance == null) 88 | { 89 | _instance = InstanceFactory(_configuration); 90 | } 91 | } 92 | } 93 | 94 | return _instance; 95 | } 96 | } 97 | 98 | static DapperExtensions() 99 | { 100 | Configure(typeof(AutoClassMapper<>), new List(), new SqlServerDialect()); 101 | } 102 | 103 | /// 104 | /// Add other assemblies that Dapper Extensions will search if a mapping is not found in the same assembly of the POCO. 105 | /// 106 | /// 107 | public static void SetMappingAssemblies(IList assemblies) 108 | { 109 | Configure(_configuration.DefaultMapper, assemblies, _configuration.Dialect); 110 | } 111 | 112 | /// 113 | /// Configure DapperExtensions extension methods. 114 | /// 115 | /// 116 | /// 117 | /// 118 | public static void Configure(IDapperExtensionsConfiguration configuration) 119 | { 120 | _instance = null; 121 | _configuration = configuration; 122 | } 123 | 124 | /// 125 | /// Configure DapperExtensions extension methods. 126 | /// 127 | /// 128 | /// 129 | /// 130 | public static void Configure(Type defaultMapper, IList mappingAssemblies, ISqlDialect sqlDialect) 131 | { 132 | Configure(new DapperExtensionsConfiguration(defaultMapper, mappingAssemblies, sqlDialect)); 133 | } 134 | 135 | /// 136 | /// Executes a query for the specified id, returning the data typed as per T 137 | /// 138 | public static T Get(this IDbConnection connection, dynamic id, IDbTransaction transaction = null, int? commandTimeout = null) where T : class 139 | { 140 | var result = Instance.Get(connection, id, transaction, commandTimeout); 141 | return (T)result; 142 | } 143 | 144 | /// 145 | /// Executes an insert query for the specified entity. 146 | /// 147 | public static void Insert(this IDbConnection connection, IEnumerable entities, IDbTransaction transaction = null, int? commandTimeout = null) where T : class 148 | { 149 | Instance.Insert(connection, entities, transaction, commandTimeout); 150 | } 151 | 152 | /// 153 | /// Executes an insert query for the specified entity, returning the primary key. 154 | /// If the entity has a single key, just the value is returned. 155 | /// If the entity has a composite key, an IDictionary<string, object> is returned with the key values. 156 | /// The key value for the entity will also be updated if the KeyType is a Guid or Identity. 157 | /// 158 | public static dynamic Insert(this IDbConnection connection, T entity, IDbTransaction transaction = null, int? commandTimeout = null) where T : class 159 | { 160 | return Instance.Insert(connection, entity, transaction, commandTimeout); 161 | } 162 | 163 | /// 164 | /// Executes an update query for the specified entity. 165 | /// 166 | public static bool Update(this IDbConnection connection, T entity, IDbTransaction transaction = null, int? commandTimeout = null) where T : class 167 | { 168 | return Instance.Update(connection, entity, transaction, commandTimeout); 169 | } 170 | 171 | /// 172 | /// Executes a delete query for the specified entity. 173 | /// 174 | public static bool Delete(this IDbConnection connection, T entity, IDbTransaction transaction = null, int? commandTimeout = null) where T : class 175 | { 176 | return Instance.Delete(connection, entity, transaction, commandTimeout); 177 | } 178 | 179 | /// 180 | /// Executes a delete query using the specified predicate. 181 | /// 182 | public static bool Delete(this IDbConnection connection, object predicate, IDbTransaction transaction = null, int? commandTimeout = null) where T : class 183 | { 184 | return Instance.Delete(connection, predicate, transaction, commandTimeout); 185 | } 186 | 187 | /// 188 | /// 使用表达式进行删除 189 | /// 190 | public static bool Delete(this IDbConnection connection, Expression> expression, IDbTransaction transaction = null, int? commandTimeout = null) where T : class 191 | { 192 | return Instance.Delete(connection, expression, transaction, commandTimeout); 193 | } 194 | 195 | /// 196 | /// Executes a select query using the specified predicate, returning an IEnumerable data typed as per T. 197 | /// 198 | public static IEnumerable GetList(this IDbConnection connection, object predicate = null, IList sort = null, IDbTransaction transaction = null, int? commandTimeout = null, bool buffered = false) where T : class 199 | { 200 | return Instance.GetList(connection, predicate, sort, transaction, commandTimeout, buffered); 201 | } 202 | 203 | /// 204 | /// 使用表达式进行查找列表 205 | /// 206 | public static IEnumerable GetList(this IDbConnection connection, Expression> expression, IList sort = null, IDbTransaction transaction = null, int? commandTimeout = null, bool buffered = false) where T : class 207 | { 208 | return Instance.GetList(connection, expression, sort, transaction, commandTimeout, buffered); 209 | } 210 | 211 | /// 212 | /// Executes a select query using the specified predicate, returning an IEnumerable data typed as per T. 213 | /// Data returned is dependent upon the specified page and resultsPerPage. 214 | /// 215 | public static IEnumerable GetPage(this IDbConnection connection, object predicate, IList sort, int page, int resultsPerPage, IDbTransaction transaction = null, int? commandTimeout = null, bool buffered = false) where T : class 216 | { 217 | return Instance.GetPage(connection, predicate, sort, page, resultsPerPage, transaction, commandTimeout, buffered); 218 | } 219 | 220 | /// 221 | /// 使用表达式进行分页查找 222 | /// 223 | public static IEnumerable GetPage(this IDbConnection connection, Expression> expression, IList sort, int page, int resultsPerPage, IDbTransaction transaction = null, int? commandTimeout = null, bool buffered = false) where T : class 224 | { 225 | return Instance.GetPage(connection, expression, sort, page, resultsPerPage, transaction, commandTimeout, buffered); 226 | } 227 | 228 | /// 229 | /// Executes a select query using the specified predicate, returning an IEnumerable data typed as per T. 230 | /// Data returned is dependent upon the specified firstResult and maxResults. 231 | /// 232 | public static IEnumerable GetSet(this IDbConnection connection, object predicate, IList sort, int firstResult, int maxResults, IDbTransaction transaction = null, int? commandTimeout = null, bool buffered = false) where T : class 233 | { 234 | return Instance.GetSet(connection, predicate, sort, firstResult, maxResults, transaction, commandTimeout, buffered); 235 | } 236 | 237 | /// 238 | /// Executes a query using the specified predicate, returning an integer that represents the number of rows that match the query. 239 | /// 240 | public static int Count(this IDbConnection connection, object predicate, IDbTransaction transaction = null, int? commandTimeout = null) where T : class 241 | { 242 | return Instance.Count(connection, predicate, transaction, commandTimeout); 243 | } 244 | 245 | public static int Count(this IDbConnection connection, Expression> expression, IDbTransaction transaction = null, int? commandTimeout = null) where T : class 246 | { 247 | return Instance.Count(connection, expression, transaction, commandTimeout); 248 | } 249 | 250 | /// 251 | /// Executes a select query for multiple objects, returning IMultipleResultReader for each predicate. 252 | /// 253 | public static IMultipleResultReader GetMultiple(this IDbConnection connection, GetMultiplePredicate predicate, IDbTransaction transaction = null, int? commandTimeout = null) 254 | { 255 | return Instance.GetMultiple(connection, predicate, transaction, commandTimeout); 256 | } 257 | 258 | /// 259 | /// Gets the appropriate mapper for the specified type T. 260 | /// If the mapper for the type is not yet created, a new mapper is generated from the mapper type specifed by DefaultMapper. 261 | /// 262 | public static IClassMapper GetMap() where T : class 263 | { 264 | return Instance.SqlGenerator.Configuration.GetMap(); 265 | } 266 | 267 | /// 268 | /// Clears the ClassMappers for each type. 269 | /// 270 | public static void ClearCache() 271 | { 272 | Instance.SqlGenerator.Configuration.ClearCache(); 273 | } 274 | 275 | /// 276 | /// Generates a COMB Guid which solves the fragmented index issue. 277 | /// See: http://davybrion.com/blog/2009/05/using-the-guidcomb-identifier-strategy 278 | /// 279 | public static Guid GetNextGuid() 280 | { 281 | return Instance.SqlGenerator.Configuration.GetNextGuid(); 282 | } 283 | } 284 | } 285 | --------------------------------------------------------------------------------