├── .editorconfig ├── .gitattributes ├── .gitignore ├── .nuget ├── NuGet.Config ├── NuGet.exe └── NuGet.targets ├── DapperDal.nuspec ├── DapperDal.sln ├── LICENSE ├── README.md ├── api ├── .gitignore ├── .manifest └── index.md ├── buildPackage.cmd ├── docfx.json ├── src └── DapperDal │ ├── DalBaseOfTEntity..cs │ ├── DalBaseOfTEntity.Count.cs │ ├── DalBaseOfTEntity.Delete.cs │ ├── DalBaseOfTEntity.Execute.OtherConn.cs │ ├── DalBaseOfTEntity.Execute.cs │ ├── DalBaseOfTEntity.ExecuteScalar.OtherConn.cs │ ├── DalBaseOfTEntity.ExecuteScalar.cs │ ├── DalBaseOfTEntity.Exsit.cs │ ├── DalBaseOfTEntity.Get.cs │ ├── DalBaseOfTEntity.GetFirst.cs │ ├── DalBaseOfTEntity.GetList.cs │ ├── DalBaseOfTEntity.GetListPaged.cs │ ├── DalBaseOfTEntity.GetSet.cs │ ├── DalBaseOfTEntity.GetTop.cs │ ├── DalBaseOfTEntity.Insert.cs │ ├── DalBaseOfTEntity.Query.OtherConn.cs │ ├── DalBaseOfTEntity.Query.cs │ ├── DalBaseOfTEntity.QueryDataSet.OtherConn.cs │ ├── DalBaseOfTEntity.QueryDataSet.cs │ ├── DalBaseOfTEntity.QueryFirst.OtherConn.cs │ ├── DalBaseOfTEntity.QueryFirst.cs │ ├── DalBaseOfTEntity.QueryMultiple.OtherConn.cs │ ├── DalBaseOfTEntity.QueryMultiple.cs │ ├── DalBaseOfTEntity.SoftDelete.cs │ ├── DalBaseOfTEntity.SwitchActive.cs │ ├── DalBaseOfTEntity.Update.cs │ ├── DalBaseOfTEntity.cs │ ├── DalConfiguration.cs │ ├── DalOptions.cs │ ├── DapperDal.csproj │ ├── Expressions │ ├── ExpressionUtility.cs │ ├── PredicateBuilder.cs │ ├── PredicateExtensions.cs │ ├── QueryBuilder.cs │ ├── QueryFunctions.cs │ ├── SortDirection.cs │ └── SortingExtensions.cs │ ├── Implementor │ └── DalImplementor.cs │ ├── Mapper │ ├── AutoClassMapper.cs │ ├── AutoEntityMapper.cs │ ├── ClassMapper.cs │ ├── PluralizedAutoClassMapper.cs │ └── PropertyMap.cs │ ├── Predicate │ ├── GetMultiplePredicate.cs │ ├── GetMultipleResult.cs │ └── Predicates.cs │ ├── Properties │ └── AssemblyInfo.cs │ ├── Sql │ ├── SqlDialectBase.cs │ ├── SqlGenerator.cs │ └── SqlServerDialect.cs │ ├── Utils │ ├── ExpressionExtensions.cs │ └── ReflectionHelper.cs │ └── packages.config ├── test ├── DapperDal.Test.Entities │ ├── DapperDal.Test.Entities.csproj │ ├── ExternallyMapped.cs │ └── Properties │ │ └── AssemblyInfo.cs ├── DapperDal.Test.Maps │ ├── DapperDal.Test.Maps.csproj │ ├── ExternallyMappedMap.cs │ └── Properties │ │ └── AssemblyInfo.cs └── DapperDal.Test │ ├── App.config │ ├── Dal │ ├── CarDal.cs │ ├── ConnectionNames.cs │ └── PersonDal.cs │ ├── DapperDal.Test.csproj │ ├── Entities │ ├── CarEntity.cs │ └── PersonEntity.cs │ ├── Helpers │ ├── DatabaseInfo.cs │ ├── Protected.cs │ └── TestHelpers.cs │ ├── IntegrationTests │ ├── NonCrudFixture.cs │ └── SqlServer │ │ ├── CrudFixture.cs │ │ ├── Sql │ │ ├── CreateCarTable.sql │ │ ├── CreateDatabase.sql │ │ ├── CreatePersonProcedure.sql │ │ ├── CreatePersonTable.sql │ │ ├── DropDatabase.sql │ │ └── TruncateTable.sql │ │ └── SqlServerBaseFixture.cs │ ├── Mapper │ ├── AutoClassMapperFixture.cs │ ├── ClassMapperFixture.cs │ ├── PluralizedAutoClassMapperFixture.cs │ └── PropertyMapFixture.cs │ ├── PredicatesFixture.cs │ ├── Properties │ └── AssemblyInfo.cs │ ├── ReflectionHelperFixture.cs │ ├── Sql │ ├── SqlDialectBaseFixture.cs │ ├── SqlGeneratorFixture.cs │ └── SqlServerDialectFixture.cs │ └── packages.config └── toc.yml /.editorconfig: -------------------------------------------------------------------------------- 1 | # EditorConfig is awesome:http://EditorConfig.org 2 | 3 | # top-most EditorConfig file 4 | root = true 5 | 6 | # Don't use tabs for indentation. 7 | [*] 8 | indent_style = space 9 | # (Please don't specify an indent_size here; that has too many unintended consequences.) 10 | 11 | # Code files 12 | [*.{cs,csx,vb,vbx}] 13 | indent_size = 4 14 | 15 | # Xml project files 16 | [*.{csproj,vbproj,vcxproj,vcxproj.filters,proj,projitems,shproj}] 17 | indent_size = 2 18 | 19 | # Xml config files 20 | [*.{props,targets,ruleset,config,nuspec,resx,vsixmanifest,vsct}] 21 | indent_size = 2 22 | 23 | # JSON files 24 | [*.json] 25 | indent_size = 2 26 | 27 | # Dotnet code style settings: 28 | [*.cs] 29 | # Sort using and Import directives with System.* appearing first 30 | dotnet_sort_system_directives_first = true 31 | 32 | # Don't use this. qualifier 33 | dotnet_style_qualification_for_field = false:suggestion 34 | dotnet_style_qualification_for_property = false:suggestion 35 | 36 | # use int x = .. over Int32 37 | dotnet_style_predefined_type_for_locals_parameters_members = true:suggestion 38 | 39 | # use int.MaxValue over Int32.MaxValue 40 | dotnet_style_predefined_type_for_member_access = true:suggestion 41 | 42 | # Require var all the time. 43 | csharp_style_var_for_built_in_types = true:suggestion 44 | csharp_style_var_when_type_is_apparent = true:suggestion 45 | csharp_style_var_elsewhere = true:suggestion 46 | 47 | # Disallow throw expressions. 48 | csharp_style_throw_expression = false:suggestion 49 | 50 | # Newline settings 51 | csharp_new_line_before_open_brace = all 52 | csharp_new_line_before_else = true 53 | csharp_new_line_before_catch = true 54 | csharp_new_line_before_finally = true 55 | csharp_new_line_before_members_in_object_initializers = true 56 | csharp_new_line_before_members_in_anonymous_types = true 57 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | *.doc diff=astextplain 2 | *.DOC diff=astextplain 3 | *.docx diff=astextplain 4 | *.DOCX diff=astextplain 5 | *.dot diff=astextplain 6 | *.DOT diff=astextplain 7 | *.pdf diff=astextplain 8 | *.PDF diff=astextplain 9 | *.rtf diff=astextplain 10 | *.RTF diff=astextplain 11 | 12 | *.jpg binary 13 | *.png binary 14 | *.gif binary 15 | 16 | *.cs text=auto diff=csharp 17 | *.vb text=auto 18 | *.resx text=auto 19 | *.c text=auto 20 | *.cpp text=auto 21 | *.cxx text=auto 22 | *.h text=auto 23 | *.hxx text=auto 24 | *.py text=auto 25 | *.rb text=auto 26 | *.java text=auto 27 | *.html text=auto 28 | *.htm text=auto 29 | *.css text=auto 30 | *.scss text=auto 31 | *.sass text=auto 32 | *.less text=auto 33 | *.js text=auto 34 | *.lisp text=auto 35 | *.clj text=auto 36 | *.sql text=auto 37 | *.php text=auto 38 | *.lua text=auto 39 | *.m text=auto 40 | *.asm text=auto 41 | *.erl text=auto 42 | *.fs text=auto 43 | *.fsx text=auto 44 | *.hs text=auto 45 | 46 | *.csproj text=auto 47 | *.vbproj text=auto 48 | *.fsproj text=auto 49 | *.dbproj text=auto 50 | *.sln text=auto eol=crlf 51 | 52 | *.sh eol=lf 53 | -------------------------------------------------------------------------------- /.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 | artifacts/ 46 | 47 | *_i.c 48 | *_p.c 49 | *_i.h 50 | *.ilk 51 | *.meta 52 | *.obj 53 | *.pch 54 | *.pdb 55 | *.pgc 56 | *.pgd 57 | *.rsp 58 | *.sbr 59 | *.tlb 60 | *.tli 61 | *.tlh 62 | *.tmp 63 | *.tmp_proj 64 | *.log 65 | *.vspscc 66 | *.vssscc 67 | .builds 68 | *.pidb 69 | *.svclog 70 | *.scc 71 | 72 | # Chutzpah Test files 73 | _Chutzpah* 74 | 75 | # Visual C++ cache files 76 | ipch/ 77 | *.aps 78 | *.ncb 79 | *.opendb 80 | *.opensdf 81 | *.sdf 82 | *.cachefile 83 | *.VC.db 84 | *.VC.VC.opendb 85 | 86 | # Visual Studio profiler 87 | *.psess 88 | *.vsp 89 | *.vspx 90 | *.sap 91 | 92 | # TFS 2012 Local Workspace 93 | $tf/ 94 | 95 | # Guidance Automation Toolkit 96 | *.gpState 97 | 98 | # ReSharper is a .NET coding add-in 99 | _ReSharper*/ 100 | *.[Rr]e[Ss]harper 101 | *.DotSettings.user 102 | 103 | # JustCode is a .NET coding add-in 104 | .JustCode 105 | 106 | # TeamCity is a build add-in 107 | _TeamCity* 108 | 109 | # DotCover is a Code Coverage Tool 110 | *.dotCover 111 | 112 | # NCrunch 113 | _NCrunch_* 114 | .*crunch*.local.xml 115 | nCrunchTemp_* 116 | 117 | # MightyMoose 118 | *.mm.* 119 | AutoTest.Net/ 120 | 121 | # Web workbench (sass) 122 | .sass-cache/ 123 | 124 | # Installshield output folder 125 | [Ee]xpress/ 126 | 127 | # DocProject is a documentation generator add-in 128 | DocProject/buildhelp/ 129 | DocProject/Help/*.HxT 130 | DocProject/Help/*.HxC 131 | DocProject/Help/*.hhc 132 | DocProject/Help/*.hhk 133 | DocProject/Help/*.hhp 134 | DocProject/Help/Html2 135 | DocProject/Help/html 136 | 137 | # Click-Once directory 138 | publish/ 139 | 140 | # Publish Web Output 141 | *.[Pp]ublish.xml 142 | *.azurePubxml 143 | # TODO: Comment the next line if you want to checkin your web deploy settings 144 | # but database connection strings (with potential passwords) will be unencrypted 145 | *.pubxml 146 | *.publishproj 147 | 148 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 149 | # checkin your Azure Web App publish settings, but sensitive information contained 150 | # in these scripts will be unencrypted 151 | PublishScripts/ 152 | 153 | # NuGet Packages 154 | #*.nupkg 155 | # The packages folder can be ignored because of Package Restore 156 | **/packages/* 157 | # except build/, which is used as an MSBuild target. 158 | !**/packages/build/ 159 | # Uncomment if necessary however generally it will be regenerated when needed 160 | #!**/packages/repositories.config 161 | # NuGet v3's project.json files produces more ignoreable files 162 | *.nuget.props 163 | *.nuget.targets 164 | 165 | # Microsoft Azure Build Output 166 | csx/ 167 | *.build.csdef 168 | 169 | # Microsoft Azure Emulator 170 | ecf/ 171 | rcf/ 172 | 173 | # Windows Store app package directories and files 174 | AppPackages/ 175 | BundleArtifacts/ 176 | Package.StoreAssociation.xml 177 | _pkginfo.txt 178 | 179 | # Visual Studio cache files 180 | # files ending in .cache can be ignored 181 | *.[Cc]ache 182 | # but keep track of directories ending in .cache 183 | !*.[Cc]ache/ 184 | 185 | # Others 186 | ClientBin/ 187 | ~$* 188 | *~ 189 | *.dbmdl 190 | *.dbproj.schemaview 191 | *.pfx 192 | *.publishsettings 193 | node_modules/ 194 | orleans.codegen.cs 195 | 196 | # Since there are multiple workflows, uncomment next line to ignore bower_components 197 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 198 | #bower_components/ 199 | 200 | # RIA/Silverlight projects 201 | Generated_Code/ 202 | 203 | # Backup & report files from converting an old project file 204 | # to a newer Visual Studio version. Backup files are not needed, 205 | # because we have git ;-) 206 | _UpgradeReport_Files/ 207 | Backup*/ 208 | UpgradeLog*.XML 209 | UpgradeLog*.htm 210 | 211 | # SQL Server files 212 | *.mdf 213 | *.ldf 214 | 215 | # Business Intelligence projects 216 | *.rdl.data 217 | *.bim.layout 218 | *.bim_*.settings 219 | 220 | # Microsoft Fakes 221 | FakesAssemblies/ 222 | 223 | # GhostDoc plugin setting file 224 | *.GhostDoc.xml 225 | 226 | # Node.js Tools for Visual Studio 227 | .ntvs_analysis.dat 228 | 229 | # Visual Studio 6 build log 230 | *.plg 231 | 232 | # Visual Studio 6 workspace options file 233 | *.opt 234 | 235 | # Visual Studio LightSwitch build output 236 | **/*.HTMLClient/GeneratedArtifacts 237 | **/*.DesktopClient/GeneratedArtifacts 238 | **/*.DesktopClient/ModelManifest.xml 239 | **/*.Server/GeneratedArtifacts 240 | **/*.Server/ModelManifest.xml 241 | _Pvt_Extensions 242 | 243 | # Paket dependency manager 244 | .paket/paket.exe 245 | paket-files/ 246 | 247 | # FAKE - F# Make 248 | .fake/ 249 | 250 | # JetBrains Rider 251 | .idea/ 252 | *.sln.iml 253 | 254 | ############### 255 | # folder # 256 | ############### 257 | /**/DROP/ 258 | /**/TEMP/ 259 | /**/packages/ 260 | /**/bin/ 261 | /**/obj/ 262 | _site -------------------------------------------------------------------------------- /.nuget/NuGet.Config: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /.nuget/NuGet.exe: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/arbing/DapperDal/bdb0beb99f3479e385bbad9970bbc4dda18ab925/.nuget/NuGet.exe -------------------------------------------------------------------------------- /.nuget/NuGet.targets: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | $(MSBuildProjectDirectory)\..\ 5 | 6 | 7 | false 8 | 9 | 10 | false 11 | 12 | 13 | true 14 | 15 | 16 | false 17 | 18 | 19 | 20 | 21 | 22 | 26 | 27 | 28 | 29 | 30 | $([System.IO.Path]::Combine($(SolutionDir), ".nuget")) 31 | $([System.IO.Path]::Combine($(ProjectDir), "packages.config")) 32 | 33 | 34 | 35 | 36 | $(SolutionDir).nuget 37 | packages.config 38 | 39 | 40 | 41 | 42 | $(NuGetToolsPath)\NuGet.exe 43 | @(PackageSource) 44 | 45 | "$(NuGetExePath)" 46 | mono --runtime=v4.0.30319 $(NuGetExePath) 47 | 48 | $(TargetDir.Trim('\\')) 49 | 50 | -RequireConsent 51 | -NonInteractive 52 | 53 | 54 | $(NuGetCommand) install "$(PackagesConfig)" -source "$(PackageSources)" $(NonInteractiveSwitch) $(RequireConsentSwitch) -solutionDir "$(SolutionDir) " 55 | $(NuGetCommand) pack "$(ProjectPath)" -Properties Configuration=$(Configuration) $(NonInteractiveSwitch) -OutputDirectory "$(PackageOutputDir)" -symbols 56 | 57 | 58 | 59 | RestorePackages; 60 | $(BuildDependsOn); 61 | 62 | 63 | 64 | 65 | $(BuildDependsOn); 66 | BuildPackage; 67 | 68 | 69 | 70 | 71 | 72 | 73 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 88 | 89 | 92 | 93 | 94 | 95 | 97 | 98 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | 110 | 111 | 112 | 113 | 114 | 115 | 130 | 131 | 132 | 133 | -------------------------------------------------------------------------------- /DapperDal.nuspec: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | DapperDal 5 | 1.5.19 6 | DapperDal 7 | arbing 8 | arbing 9 | http://www.apache.org/licenses/LICENSE-2.0 10 | https://github.com/arbing/DapperDal 11 | 12 | false 13 | 基于 Dapper、Dapper-Extensions 构建的微型 ORM 类库,提供一个包含增、删、改、查等常用方法的数据访问层基类,支持用 Lambda 表达式书写查询和更新条件 14 | 基于 Dapper、Dapper-Extensions 构建的微型 ORM 类库,提供一个包含增、删、改、查等常用方法的数据访问层基类,支持用 Lambda 表达式书写查询和更新条件 15 | 16 | 1.5.19 17 | * 逻辑删除方法 SoftDelete、SwitchActive 默认更新字段 UpdateTime = DateTime.Now 18 | 1.5.18 19 | * 添加返回 DataSet 的查询方法:QueryDataSet 20 | 1.5.16 21 | * 重构,合并 Dapper-Extensions 到 DapperDal,然后移除 Dapper-Extensions 22 | 1.5.15 23 | * 删除方法 QueryFirstOrDefault,可以使用 QueryFirst 替换 24 | * 添加重载方法 OpenConnection、Execute、Query, 支持传入其他 DB 连接串 25 | 1.5.14 26 | * 添加逻辑删除或激活方法 SwitchActive 27 | * 删除方法 GetFirstOrDefault,可以使用 GetFirst 替换 28 | * 添加支持主键 ID 的重载方法 Update、Delete 29 | * 配置项 SoftDeleteProp 迁移到 DapperDal 中,新添加配置项 SoftActiveProps 30 | 1.5.13 31 | * 添加谓词表达式组合扩展方法(来自alexfoxgill/ExpressionTools) 32 | 1.5.12 33 | * 优化 Exsit 、Count 方法 34 | 1.5.11 35 | * 优化更新方法,支持传递小写字段名 36 | * 添加判断实体是否存在方法:Exsit 37 | 1.5.10 38 | * 添加逻辑删除方法 SoftDeleteById 39 | 1.5.9 40 | * 添加实体查询方法:GetFirstOrDefault 、QueryFirstOrDefault 、QueryFirst 41 | 1.5.8 42 | * 添加SQL执行方法:Execute 、ExecuteScalar 43 | 1.5.7 44 | * 添加实体查询方法:GetFirst 、GetTop 45 | * 优化实体查询方法,添加实体集合返回前是否要缓冲的设置点 46 | * 优化逻辑删除,添加更新属性及值的设置点 47 | 1.5.6 48 | * 生成查询 SQL 时,添加 WITH (NOLOCK) 49 | * 添加设置项:SQL 输出方法 50 | 1.5.5 51 | * 添加逻辑删除方法 SoftDelete 52 | 1.5.4 53 | * 表达式转换用 QueryBuilder 替换 ExpressionVisitor 实现,以支持多个查询条件 54 | 1.5.3 55 | * 添加支持多个实体查询的 Query 方法 56 | 1.5.2 57 | * 添加更新部分属性的 Update 方法(来自vilix13/Dapper-Extensions) 58 | * 添加使用谓词、匿名对象或 lambda 表达式作条件的 Update 方法 59 | 1.5.1 60 | * 整合 Abp.Dapper,为 Dapper-Extensions 添加 lambda 表达式功能(来自Abp.Dapper) 61 | 62 | Dapper orm sql micro-orm Data DAL Dapper-Extensions Abp.Dapper 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | -------------------------------------------------------------------------------- /DapperDal.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio 15 4 | VisualStudioVersion = 15.0.26430.12 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DapperDal", "src\DapperDal\DapperDal.csproj", "{64CCA848-7660-43EE-ABAE-91EFFE765E41}" 7 | EndProject 8 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DapperDal.Test", "test\DapperDal.Test\DapperDal.Test.csproj", "{8BF8684B-E2F2-43A3-B5C7-B9C49F1810C5}" 9 | EndProject 10 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{FF445554-FEE7-45CD-B9A8-1D1D80D9744F}" 11 | ProjectSection(SolutionItems) = preProject 12 | buildPackage.cmd = buildPackage.cmd 13 | DapperDal.nuspec = DapperDal.nuspec 14 | README.md = README.md 15 | EndProjectSection 16 | EndProject 17 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "test", "test", "{2AD48036-181F-4A7F-BEF8-33951AC23342}" 18 | EndProject 19 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{2E5DF445-A607-4C9F-A786-E92768186801}" 20 | EndProject 21 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DapperDal.Test.Entities", "test\DapperDal.Test.Entities\DapperDal.Test.Entities.csproj", "{1EF2B04A-7E97-4C53-8AFB-D90E815CFB05}" 22 | EndProject 23 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DapperDal.Test.Maps", "test\DapperDal.Test.Maps\DapperDal.Test.Maps.csproj", "{E335BE03-0A91-4A41-8631-71044CC46310}" 24 | EndProject 25 | Global 26 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 27 | Debug|Any CPU = Debug|Any CPU 28 | Release|Any CPU = Release|Any CPU 29 | EndGlobalSection 30 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 31 | {64CCA848-7660-43EE-ABAE-91EFFE765E41}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 32 | {64CCA848-7660-43EE-ABAE-91EFFE765E41}.Debug|Any CPU.Build.0 = Debug|Any CPU 33 | {64CCA848-7660-43EE-ABAE-91EFFE765E41}.Release|Any CPU.ActiveCfg = Release|Any CPU 34 | {64CCA848-7660-43EE-ABAE-91EFFE765E41}.Release|Any CPU.Build.0 = Release|Any CPU 35 | {8BF8684B-E2F2-43A3-B5C7-B9C49F1810C5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 36 | {8BF8684B-E2F2-43A3-B5C7-B9C49F1810C5}.Debug|Any CPU.Build.0 = Debug|Any CPU 37 | {8BF8684B-E2F2-43A3-B5C7-B9C49F1810C5}.Release|Any CPU.ActiveCfg = Release|Any CPU 38 | {8BF8684B-E2F2-43A3-B5C7-B9C49F1810C5}.Release|Any CPU.Build.0 = Release|Any CPU 39 | {1EF2B04A-7E97-4C53-8AFB-D90E815CFB05}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 40 | {1EF2B04A-7E97-4C53-8AFB-D90E815CFB05}.Debug|Any CPU.Build.0 = Debug|Any CPU 41 | {1EF2B04A-7E97-4C53-8AFB-D90E815CFB05}.Release|Any CPU.ActiveCfg = Release|Any CPU 42 | {1EF2B04A-7E97-4C53-8AFB-D90E815CFB05}.Release|Any CPU.Build.0 = Release|Any CPU 43 | {E335BE03-0A91-4A41-8631-71044CC46310}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 44 | {E335BE03-0A91-4A41-8631-71044CC46310}.Debug|Any CPU.Build.0 = Debug|Any CPU 45 | {E335BE03-0A91-4A41-8631-71044CC46310}.Release|Any CPU.ActiveCfg = Release|Any CPU 46 | {E335BE03-0A91-4A41-8631-71044CC46310}.Release|Any CPU.Build.0 = Release|Any CPU 47 | EndGlobalSection 48 | GlobalSection(SolutionProperties) = preSolution 49 | HideSolutionNode = FALSE 50 | EndGlobalSection 51 | GlobalSection(NestedProjects) = preSolution 52 | {64CCA848-7660-43EE-ABAE-91EFFE765E41} = {2E5DF445-A607-4C9F-A786-E92768186801} 53 | {8BF8684B-E2F2-43A3-B5C7-B9C49F1810C5} = {2AD48036-181F-4A7F-BEF8-33951AC23342} 54 | {1EF2B04A-7E97-4C53-8AFB-D90E815CFB05} = {2AD48036-181F-4A7F-BEF8-33951AC23342} 55 | {E335BE03-0A91-4A41-8631-71044CC46310} = {2AD48036-181F-4A7F-BEF8-33951AC23342} 56 | EndGlobalSection 57 | EndGlobal 58 | -------------------------------------------------------------------------------- /api/.gitignore: -------------------------------------------------------------------------------- 1 | ############### 2 | # temp file # 3 | ############### 4 | *.yml 5 | -------------------------------------------------------------------------------- /api/index.md: -------------------------------------------------------------------------------- 1 | # Api Documentation 2 | -------------------------------------------------------------------------------- /buildPackage.cmd: -------------------------------------------------------------------------------- 1 | @call "C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\Common7\Tools\VsDevCmd.bat" 2 | MSBuild src\DapperDal\DapperDal.csproj /t:Clean;Rebuild /p:Configuration=Release 3 | .nuget\nuget.exe pack DapperDal.nuspec /o releases -------------------------------------------------------------------------------- /docfx.json: -------------------------------------------------------------------------------- 1 | { 2 | "metadata": [{ 3 | "src": [{ 4 | "files": [ 5 | "src/**.csproj" 6 | ], 7 | "exclude": [ 8 | "**/obj/**", 9 | "**/bin/**", 10 | "_site/**" 11 | ] 12 | }], 13 | "dest": "api" 14 | }], 15 | "build": { 16 | "content": [{ 17 | "files": [ 18 | "api/**.yml", 19 | "api/index.md" 20 | ] 21 | }, 22 | { 23 | "files": [ 24 | "toc.yml", 25 | "*.md" 26 | ], 27 | "exclude": [ 28 | "obj/**", 29 | "_site/**" 30 | ] 31 | } 32 | ], 33 | "resource": [{ 34 | "files": [ 35 | "images/**" 36 | ], 37 | "exclude": [ 38 | "obj/**", 39 | "_site/**" 40 | ] 41 | }], 42 | "overwrite": [{ 43 | "files": [ 44 | "apidoc/**.md" 45 | ], 46 | "exclude": [ 47 | "obj/**", 48 | "_site/**" 49 | ] 50 | }], 51 | "dest": "_site", 52 | "globalMetadataFiles": [], 53 | "fileMetadataFiles": [], 54 | "template": [ 55 | "default" 56 | ], 57 | "postProcessors": [], 58 | "noLangKeyword": false, 59 | "keepFileLink": false, 60 | "cleanupCacheHistory": false 61 | } 62 | } -------------------------------------------------------------------------------- /src/DapperDal/DalBaseOfTEntity..cs: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/arbing/DapperDal/bdb0beb99f3479e385bbad9970bbc4dda18ab925/src/DapperDal/DalBaseOfTEntity..cs -------------------------------------------------------------------------------- /src/DapperDal/DalBaseOfTEntity.Count.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Linq.Expressions; 3 | using DapperDal.Expressions; 4 | 5 | namespace DapperDal 6 | { 7 | public partial class DalBase where TEntity : class 8 | { 9 | /// 10 | /// 获取实体条数 11 | /// 12 | /// 实体条数 13 | public virtual int Count() 14 | { 15 | using (var connection = OpenConnection()) 16 | { 17 | return Configuration.DalImplementor.Count( 18 | connection: connection, 19 | predicate: null, 20 | transaction: null, 21 | commandTimeout: null); 22 | } 23 | } 24 | 25 | /// 26 | /// 根据条件获取实体条数 27 | /// (条件使用谓词或匿名对象) 28 | /// 29 | /// 条件,使用谓词或匿名对象 30 | /// 实体条数 31 | public virtual int Count(object predicate) 32 | { 33 | using (var connection = OpenConnection()) 34 | { 35 | return Configuration.DalImplementor.Count( 36 | connection: connection, 37 | predicate: predicate, 38 | transaction: null, 39 | commandTimeout: null); 40 | } 41 | } 42 | 43 | /// 44 | /// 根据条件获取实体条数 45 | /// (条件使用表达式) 46 | /// 47 | /// 条件,使用表达式 48 | /// 实体条数 49 | public virtual int Count(Expression> predicate) 50 | { 51 | using (var connection = OpenConnection()) 52 | { 53 | var predicateGp = predicate.ToPredicateGroup(); 54 | return Configuration.DalImplementor.Count( 55 | connection: connection, 56 | predicate: predicateGp, 57 | transaction: null, 58 | commandTimeout: null); 59 | } 60 | } 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /src/DapperDal/DalBaseOfTEntity.Delete.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Linq.Expressions; 3 | using DapperDal.Expressions; 4 | using DapperDal.Predicate; 5 | 6 | namespace DapperDal 7 | { 8 | public partial class DalBase where TEntity : class 9 | { 10 | /// 11 | /// 删除指定实体 12 | /// 13 | /// 实体 14 | /// 删除结果 15 | public virtual bool Delete(TEntity entity) 16 | { 17 | using (var connection = OpenConnection()) 18 | { 19 | return Configuration.DalImplementor.Delete( 20 | connection: connection, 21 | entity: entity, 22 | transaction: null, 23 | commandTimeout: null); 24 | } 25 | } 26 | 27 | /// 28 | /// 根据实体主键ID删除指定实体 29 | /// 30 | /// 实体主键ID 31 | /// 删除结果 32 | public virtual bool Delete(TPrimaryKey id) 33 | { 34 | using (var connection = OpenConnection()) 35 | { 36 | IPredicate predicate = Configuration.DalImplementor.GetIdPredicate(id); 37 | 38 | return Configuration.DalImplementor.Delete( 39 | connection: connection, 40 | predicate: predicate, 41 | transaction: null, 42 | commandTimeout: null); 43 | } 44 | } 45 | 46 | /// 47 | /// 根据条件删除实体 48 | /// 49 | /// 删除条件 50 | /// 删除结果 51 | public virtual bool Delete(object predicate) 52 | { 53 | using (var connection = OpenConnection()) 54 | { 55 | return Configuration.DalImplementor.Delete( 56 | connection: connection, 57 | predicate: predicate, 58 | transaction: null, 59 | commandTimeout: null); 60 | } 61 | } 62 | 63 | /// 64 | /// 根据条件删除实体 65 | /// 66 | /// 删除条件 67 | /// 删除结果 68 | public virtual bool Delete(Expression> predicate) 69 | { 70 | using (var connection = OpenConnection()) 71 | { 72 | var predicateGp = predicate.ToPredicateGroup(); 73 | 74 | return Configuration.DalImplementor.Delete( 75 | connection: connection, 76 | predicate: predicateGp, 77 | transaction: null, 78 | commandTimeout: null); 79 | } 80 | } 81 | } 82 | } 83 | -------------------------------------------------------------------------------- /src/DapperDal/DalBaseOfTEntity.Execute.OtherConn.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Data; 4 | using System.Linq; 5 | using System.Text; 6 | using Dapper; 7 | 8 | namespace DapperDal 9 | { 10 | public partial class DalBase where TEntity : class 11 | { 12 | /// 13 | /// 执行SQL语句 14 | /// 15 | /// DB 连接字符串配置节点名 16 | /// SQL语句 17 | /// 影响行数 18 | public virtual int Execute(string connNameOrConnStr, string sql) 19 | { 20 | using (var connection = OpenConnection(connNameOrConnStr)) 21 | { 22 | return connection.Execute(sql); 23 | } 24 | } 25 | 26 | /// 27 | /// 执行参数化SQL语句 28 | /// 29 | /// DB 连接字符串配置节点名 30 | /// SQL语句 31 | /// SQL参数 32 | /// 影响行数 33 | public virtual int Execute(string connNameOrConnStr, string sql, object parameters) 34 | { 35 | using (var connection = OpenConnection(connNameOrConnStr)) 36 | { 37 | return connection.Execute(sql, parameters); 38 | } 39 | } 40 | 41 | /// 42 | /// 执行参数化SQL语句 43 | /// 44 | /// DB 连接字符串配置节点名 45 | /// SQL语句 46 | /// SQL参数 47 | /// SQL语句命令类型 48 | /// 影响行数 49 | public virtual int Execute(string connNameOrConnStr, string sql, object parameters, CommandType commandType) 50 | { 51 | using (var connection = OpenConnection(connNameOrConnStr)) 52 | { 53 | return connection.Execute(sql, parameters, commandType: commandType); 54 | } 55 | } 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /src/DapperDal/DalBaseOfTEntity.Execute.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Data; 4 | using System.Linq; 5 | using System.Text; 6 | using Dapper; 7 | 8 | namespace DapperDal 9 | { 10 | public partial class DalBase where TEntity : class 11 | { 12 | /// 13 | /// 执行SQL语句 14 | /// 15 | /// SQL语句 16 | /// 影响行数 17 | public virtual int Execute(string sql) 18 | { 19 | using (var connection = OpenConnection()) 20 | { 21 | return connection.Execute(sql); 22 | } 23 | } 24 | 25 | /// 26 | /// 执行参数化SQL语句 27 | /// 28 | /// SQL语句 29 | /// SQL参数 30 | /// 影响行数 31 | public virtual int Execute(string sql, object parameters) 32 | { 33 | using (var connection = OpenConnection()) 34 | { 35 | return connection.Execute(sql, parameters); 36 | } 37 | } 38 | 39 | /// 40 | /// 执行参数化SQL语句 41 | /// 42 | /// SQL语句 43 | /// SQL参数 44 | /// SQL语句命令类型 45 | /// 影响行数 46 | public virtual int Execute(string sql, object parameters, CommandType commandType) 47 | { 48 | using (var connection = OpenConnection()) 49 | { 50 | return connection.Execute(sql, parameters, commandType: commandType); 51 | } 52 | } 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /src/DapperDal/DalBaseOfTEntity.ExecuteScalar.OtherConn.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Data; 4 | using System.Linq; 5 | using System.Text; 6 | using Dapper; 7 | 8 | namespace DapperDal 9 | { 10 | public partial class DalBase where TEntity : class 11 | { 12 | /// 13 | /// 执行SQL语句,返回第一行第一列数据 14 | /// 15 | /// 返回数据类型 16 | /// DB 连接字符串配置节点名 17 | /// SQL语句 18 | /// 第一行第一列数据 19 | public virtual TAny ExecuteScalar(string connNameOrConnStr, string sql) 20 | { 21 | using (var connection = OpenConnection(connNameOrConnStr)) 22 | { 23 | return connection.ExecuteScalar(sql); 24 | } 25 | } 26 | 27 | /// 28 | /// 执行参数化SQL语句,返回第一行第一列数据 29 | /// 30 | /// 返回数据类型 31 | /// DB 连接字符串配置节点名 32 | /// SQL语句 33 | /// SQL参数 34 | /// 第一行第一列数据 35 | public virtual TAny ExecuteScalar(string connNameOrConnStr, string sql, object parameters) 36 | { 37 | using (var connection = OpenConnection(connNameOrConnStr)) 38 | { 39 | return connection.ExecuteScalar(sql, parameters); 40 | } 41 | } 42 | 43 | /// 44 | /// 执行参数化SQL语句,返回第一行第一列数据 45 | /// 46 | /// 返回数据类型 47 | /// DB 连接字符串配置节点名 48 | /// SQL语句 49 | /// SQL参数 50 | /// SQL语句命令类型 51 | /// 第一行第一列数据 52 | public virtual TAny ExecuteScalar(string connNameOrConnStr, string sql, object parameters, CommandType commandType) 53 | { 54 | using (var connection = OpenConnection(connNameOrConnStr)) 55 | { 56 | return connection.ExecuteScalar(sql, parameters, commandType: commandType); 57 | } 58 | } 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /src/DapperDal/DalBaseOfTEntity.ExecuteScalar.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Data; 4 | using System.Linq; 5 | using System.Text; 6 | using Dapper; 7 | 8 | namespace DapperDal 9 | { 10 | public partial class DalBase where TEntity : class 11 | { 12 | /// 13 | /// 执行SQL语句,返回第一行第一列数据 14 | /// 15 | /// 返回数据类型 16 | /// SQL语句 17 | /// 第一行第一列数据 18 | public virtual TAny ExecuteScalar(string sql) 19 | { 20 | using (var connection = OpenConnection()) 21 | { 22 | return connection.ExecuteScalar(sql); 23 | } 24 | } 25 | 26 | /// 27 | /// 执行参数化SQL语句,返回第一行第一列数据 28 | /// 29 | /// 返回数据类型 30 | /// SQL语句 31 | /// SQL参数 32 | /// 第一行第一列数据 33 | public virtual TAny ExecuteScalar(string sql, object parameters) 34 | { 35 | using (var connection = OpenConnection()) 36 | { 37 | return connection.ExecuteScalar(sql, parameters); 38 | } 39 | } 40 | 41 | /// 42 | /// 执行参数化SQL语句,返回第一行第一列数据 43 | /// 44 | /// 返回数据类型 45 | /// SQL语句 46 | /// SQL参数 47 | /// SQL语句命令类型 48 | /// 第一行第一列数据 49 | public virtual TAny ExecuteScalar(string sql, object parameters, CommandType commandType) 50 | { 51 | using (var connection = OpenConnection()) 52 | { 53 | return connection.ExecuteScalar(sql, parameters, commandType: commandType); 54 | } 55 | } 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /src/DapperDal/DalBaseOfTEntity.Exsit.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Linq.Expressions; 3 | using DapperDal.Expressions; 4 | using DapperDal.Predicate; 5 | 6 | namespace DapperDal 7 | { 8 | public partial class DalBase where TEntity : class 9 | { 10 | /// 11 | /// 判断实体是否存在 12 | /// 13 | /// 是否存在 14 | public virtual bool Exsit() 15 | { 16 | using (var connection = OpenConnection()) 17 | { 18 | return Configuration.DalImplementor.Count( 19 | connection: connection, 20 | predicate: null, 21 | transaction: null, 22 | commandTimeout: null) > 0; 23 | } 24 | } 25 | 26 | /// 27 | /// 判断指定主键ID的实体是否存在 28 | /// 29 | /// 实体主键ID 30 | /// 是否存在 31 | public virtual bool Exsit(TPrimaryKey id) 32 | { 33 | using (var connection = OpenConnection()) 34 | { 35 | IPredicate predicate = Configuration.DalImplementor.GetIdPredicate(id); 36 | return Configuration.DalImplementor.Count( 37 | connection: connection, 38 | predicate: predicate, 39 | transaction: null, 40 | commandTimeout: null) > 0; 41 | } 42 | } 43 | 44 | /// 45 | /// 判断指定条件的实体是否存在 46 | /// (条件使用谓词或匿名对象) 47 | /// 48 | /// 条件,使用谓词或匿名对象 49 | /// 是否存在 50 | public virtual bool Exsit(object predicate) 51 | { 52 | using (var connection = OpenConnection()) 53 | { 54 | return Configuration.DalImplementor.Count( 55 | connection: connection, 56 | predicate: predicate, 57 | transaction: null, 58 | commandTimeout: null) > 0; 59 | } 60 | } 61 | 62 | /// 63 | /// 判断指定条件的实体是否存在 64 | /// (条件使用表达式) 65 | /// 66 | /// 条件,使用表达式 67 | /// 是否存在 68 | public virtual bool Exsit(Expression> predicate) 69 | { 70 | using (var connection = OpenConnection()) 71 | { 72 | var predicateGp = predicate.ToPredicateGroup(); 73 | return Configuration.DalImplementor.Count( 74 | connection: connection, 75 | predicate: predicateGp, 76 | transaction: null, 77 | commandTimeout: null) > 0; 78 | } 79 | } 80 | } 81 | } 82 | -------------------------------------------------------------------------------- /src/DapperDal/DalBaseOfTEntity.Get.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Linq.Expressions; 5 | using System.Text; 6 | 7 | namespace DapperDal 8 | { 9 | public partial class DalBase where TEntity : class 10 | { 11 | /// 12 | /// 根据实体ID(主键)获取实体 13 | /// 14 | /// 实体ID 15 | /// 实体 16 | public virtual TEntity Get(TPrimaryKey id) 17 | { 18 | using (var connection = OpenConnection()) 19 | { 20 | return Configuration.DalImplementor.Get( 21 | connection: connection, 22 | id: id, 23 | transaction: null, 24 | commandTimeout: null); 25 | } 26 | } 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/DapperDal/DalBaseOfTEntity.GetList.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq.Expressions; 4 | using DapperDal.Expressions; 5 | 6 | namespace DapperDal 7 | { 8 | public partial class DalBase where TEntity : class 9 | { 10 | /// 11 | /// 获取所有实体列表 12 | /// 13 | /// 实体列表 14 | public virtual IEnumerable GetList() 15 | { 16 | using (var connection = OpenConnection()) 17 | { 18 | return Configuration.DalImplementor.GetList( 19 | connection: connection, 20 | predicate: null, 21 | sort: null, 22 | transaction: null, 23 | commandTimeout: null, 24 | buffered: Configuration.Buffered); 25 | } 26 | } 27 | 28 | /// 29 | /// 根据查询条件获取实体列表 30 | /// (查询使用谓词或匿名对象) 31 | /// 32 | /// 查询条件 33 | /// 实体列表 34 | public virtual IEnumerable GetList(object predicate) 35 | { 36 | using (var connection = OpenConnection()) 37 | { 38 | return Configuration.DalImplementor.GetList( 39 | connection: connection, 40 | predicate: predicate, 41 | sort: null, 42 | transaction: null, 43 | commandTimeout: null, 44 | buffered: Configuration.Buffered); 45 | } 46 | } 47 | 48 | /// 49 | /// 根据排序条件获取所有实体列表 50 | /// (排序使用表达式) 51 | /// 52 | /// 排序方向 53 | /// 排序字段 54 | /// 实体列表 55 | public virtual IEnumerable GetList(SortDirection ascending, 56 | params Expression>[] sortingExpression) 57 | { 58 | using (var connection = OpenConnection()) 59 | { 60 | var sort = sortingExpression.ToSortable(ascending); 61 | return Configuration.DalImplementor.GetList( 62 | connection: connection, 63 | predicate: null, 64 | sort: sort, 65 | transaction: null, 66 | commandTimeout: null, 67 | buffered: Configuration.Buffered); 68 | } 69 | } 70 | 71 | /// 72 | /// 根据查询条件和排序条件获取实体列表 73 | /// (查询使用谓词或匿名对象,排序使用Sort或匿名对象) 74 | /// 75 | /// 查询条件 76 | /// 排序条件 77 | /// 实体列表 78 | public virtual IEnumerable GetList(object predicate, object sort) 79 | { 80 | using (var connection = OpenConnection()) 81 | { 82 | var sorts = sort.ToSortable(); 83 | return Configuration.DalImplementor.GetList( 84 | connection: connection, 85 | predicate: predicate, 86 | sort: sorts, 87 | transaction: null, 88 | commandTimeout: null, 89 | buffered: Configuration.Buffered); 90 | } 91 | } 92 | 93 | /// 94 | /// 根据查询条件和排序条件获取实体列表 95 | /// (查询使用谓词或匿名对象,排序使用表达式) 96 | /// 97 | /// 查询条件 98 | /// 排序方向 99 | /// 排序字段 100 | /// 实体列表 101 | public virtual IEnumerable GetList(object predicate, 102 | SortDirection ascending, 103 | params Expression>[] sortingExpression) 104 | { 105 | using (var connection = OpenConnection()) 106 | { 107 | var sort = sortingExpression.ToSortable(ascending); 108 | return Configuration.DalImplementor.GetList( 109 | connection: connection, 110 | predicate: predicate, 111 | sort: sort, 112 | transaction: null, 113 | commandTimeout: null, 114 | buffered: Configuration.Buffered); 115 | } 116 | } 117 | 118 | /// 119 | /// 根据查询条件获取实体列表 120 | /// (查询使用表达式) 121 | /// 122 | /// 查询条件 123 | /// 实体列表 124 | public virtual IEnumerable GetList(Expression> predicate) 125 | { 126 | using (var connection = OpenConnection()) 127 | { 128 | var predicateGp = predicate.ToPredicateGroup(); 129 | return Configuration.DalImplementor.GetList( 130 | connection: connection, 131 | predicate: predicateGp, 132 | sort: null, 133 | transaction: null, 134 | commandTimeout: null, 135 | buffered: Configuration.Buffered); 136 | } 137 | } 138 | 139 | /// 140 | /// 根据查询条件和排序条件获取实体列表 141 | /// (查询使用表达式,排序使用Sort或匿名对象) 142 | /// 143 | /// 查询条件 144 | /// 排序条件 145 | /// 实体列表 146 | public virtual IEnumerable GetList(Expression> predicate, object sort) 147 | { 148 | using (var connection = OpenConnection()) 149 | { 150 | var predicateGp = predicate.ToPredicateGroup(); 151 | var sorts = sort.ToSortable(); 152 | return Configuration.DalImplementor.GetList( 153 | connection: connection, 154 | predicate: predicateGp, 155 | sort: sorts, 156 | transaction: null, 157 | commandTimeout: null, 158 | buffered: Configuration.Buffered); 159 | } 160 | } 161 | 162 | /// 163 | /// 根据查询条件和排序条件获取实体列表 164 | /// (查询使用表达式,排序使用表达式) 165 | /// 166 | /// 查询条件 167 | /// 排序方向 168 | /// 排序字段 169 | /// 实体列表 170 | public virtual IEnumerable GetList(Expression> predicate, 171 | SortDirection ascending, 172 | params Expression>[] sortingExpression) 173 | { 174 | using (var connection = OpenConnection()) 175 | { 176 | var predicateGp = predicate.ToPredicateGroup(); 177 | var sort = sortingExpression.ToSortable(ascending); 178 | return Configuration.DalImplementor.GetList( 179 | connection: connection, 180 | predicate: predicateGp, 181 | sort: sort, 182 | transaction: null, 183 | commandTimeout: null, 184 | buffered: Configuration.Buffered); 185 | } 186 | } 187 | } 188 | } 189 | -------------------------------------------------------------------------------- /src/DapperDal/DalBaseOfTEntity.GetListPaged.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq.Expressions; 4 | using DapperDal.Expressions; 5 | 6 | namespace DapperDal 7 | { 8 | public partial class DalBase where TEntity : class 9 | { 10 | /// 11 | /// 根据查询条件和排序条件获取实体分页列表 12 | /// (查询使用谓词或匿名对象,排序使用Sort或匿名对象) 13 | /// 14 | /// 查询条件 15 | /// 排序条件 16 | /// 页号,从1起始 17 | /// 每页条数 18 | /// 实体分页列表 19 | public virtual IEnumerable GetListPaged(object predicate, object sort, 20 | int pageNumber, int itemsPerPage) 21 | { 22 | using (var connection = OpenConnection()) 23 | { 24 | var sorts = sort.ToSortable(); 25 | return Configuration.DalImplementor.GetPage( 26 | connection: connection, 27 | predicate: predicate, 28 | sort: sorts, 29 | page: pageNumber - 1, 30 | resultsPerPage: itemsPerPage, 31 | transaction: null, 32 | commandTimeout: null, 33 | buffered: Configuration.Buffered); 34 | } 35 | } 36 | 37 | /// 38 | /// 根据查询条件和排序条件获取实体分页列表 39 | /// (查询使用谓词或匿名对象,排序表达式) 40 | /// 41 | /// 查询条件 42 | /// 页号,从1起始 43 | /// 每页条数 44 | /// 排序方向 45 | /// 排序字段 46 | /// 实体分页列表 47 | public virtual IEnumerable GetListPaged(object predicate, 48 | int pageNumber, int itemsPerPage, 49 | SortDirection ascending, 50 | params Expression>[] sortingExpression) 51 | { 52 | using (var connection = OpenConnection()) 53 | { 54 | var sort = sortingExpression.ToSortable(ascending); 55 | return Configuration.DalImplementor.GetPage( 56 | connection: connection, 57 | predicate: predicate, 58 | sort: sort, 59 | page: pageNumber - 1, 60 | resultsPerPage: itemsPerPage, 61 | transaction: null, 62 | commandTimeout: null, 63 | buffered: Configuration.Buffered); 64 | } 65 | } 66 | 67 | /// 68 | /// 根据查询条件和排序条件获取实体分页列表 69 | /// (查询使用表达式,排序使用Sort或匿名对象) 70 | /// 71 | /// 查询条件 72 | /// 排序条件 73 | /// 页号,从1起始 74 | /// 每页条数 75 | /// 实体分页列表 76 | public virtual IEnumerable GetListPaged(Expression> predicate, object sort, 77 | int pageNumber, int itemsPerPage) 78 | { 79 | using (var connection = OpenConnection()) 80 | { 81 | var predicateGp = predicate.ToPredicateGroup(); 82 | var sorts = sort.ToSortable(); 83 | return Configuration.DalImplementor.GetPage( 84 | connection: connection, 85 | predicate: predicateGp, 86 | sort: sorts, 87 | page: pageNumber - 1, 88 | resultsPerPage: itemsPerPage, 89 | transaction: null, 90 | commandTimeout: null, 91 | buffered: Configuration.Buffered); 92 | } 93 | } 94 | 95 | /// 96 | /// 根据查询条件和排序条件获取实体分页列表 97 | /// (查询使用表达式,排序使用表达式) 98 | /// 99 | /// 查询条件 100 | /// 页号,从1起始 101 | /// 每页条数 102 | /// 排序方向 103 | /// 排序字段 104 | /// 实体分页列表 105 | public virtual IEnumerable GetListPaged(Expression> predicate, 106 | int pageNumber, int itemsPerPage, 107 | SortDirection ascending, 108 | params Expression>[] sortingExpression) 109 | { 110 | using (var connection = OpenConnection()) 111 | { 112 | var predicateGp = predicate.ToPredicateGroup(); 113 | var sort = sortingExpression.ToSortable(ascending); 114 | return Configuration.DalImplementor.GetPage( 115 | connection: connection, 116 | predicate: predicateGp, 117 | sort: sort, 118 | page: pageNumber - 1, 119 | resultsPerPage: itemsPerPage, 120 | transaction: null, 121 | commandTimeout: null, 122 | buffered: Configuration.Buffered); 123 | } 124 | } 125 | } 126 | } 127 | -------------------------------------------------------------------------------- /src/DapperDal/DalBaseOfTEntity.GetSet.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq.Expressions; 4 | using DapperDal.Expressions; 5 | 6 | namespace DapperDal 7 | { 8 | public partial class DalBase where TEntity : class 9 | { 10 | /// 11 | /// 根据查询条件和排序条件获取实体区间列表 12 | /// (查询使用谓词或匿名对象,排序使用Sort或匿名对象) 13 | /// 14 | /// 查询条件 15 | /// 排序条件 16 | /// 起始行数 17 | /// 最大条数 18 | /// 实体区间列表 19 | public virtual IEnumerable GetSet(object predicate, object sort, 20 | int firstResult, int maxResults) 21 | { 22 | using (var connection = OpenConnection()) 23 | { 24 | var sorts = sort.ToSortable(); 25 | return Configuration.DalImplementor.GetSet( 26 | connection: connection, 27 | predicate: predicate, 28 | sort: sorts, 29 | firstResult: firstResult, 30 | maxResults: maxResults, 31 | transaction: null, 32 | commandTimeout: null, 33 | buffered: Configuration.Buffered); 34 | } 35 | } 36 | 37 | /// 38 | /// 根据查询条件和排序条件获取实体区间列表 39 | /// (查询使用谓词或匿名对象,排序表达式) 40 | /// 41 | /// 查询条件 42 | /// 起始行数 43 | /// 最大条数 44 | /// 排序方向 45 | /// 排序字段 46 | /// 实体区间列表 47 | public virtual IEnumerable GetSet(object predicate, 48 | int firstResult, int maxResults, 49 | SortDirection ascending, 50 | params Expression>[] sortingExpression) 51 | { 52 | using (var connection = OpenConnection()) 53 | { 54 | var sort = sortingExpression.ToSortable(ascending); 55 | return Configuration.DalImplementor.GetSet( 56 | connection: connection, 57 | predicate: predicate, 58 | sort: sort, 59 | firstResult: firstResult, 60 | maxResults: maxResults, 61 | transaction: null, 62 | commandTimeout: null, 63 | buffered: Configuration.Buffered); 64 | } 65 | } 66 | 67 | /// 68 | /// 根据查询条件和排序条件获取实体区间列表 69 | /// (查询使用表达式,排序使用Sort或匿名对象) 70 | /// 71 | /// 查询条件 72 | /// 排序条件 73 | /// 起始行数 74 | /// 最大条数 75 | /// 实体区间列表 76 | public virtual IEnumerable GetSet(Expression> predicate, object sort, 77 | int firstResult, int maxResults) 78 | { 79 | using (var connection = OpenConnection()) 80 | { 81 | var predicateGp = predicate.ToPredicateGroup(); 82 | var sorts = sort.ToSortable(); 83 | return Configuration.DalImplementor.GetSet( 84 | connection: connection, 85 | predicate: predicateGp, 86 | sort: sorts, 87 | firstResult: firstResult, 88 | maxResults: maxResults, 89 | transaction: null, 90 | commandTimeout: null, 91 | buffered: Configuration.Buffered); 92 | } 93 | } 94 | 95 | /// 96 | /// 根据查询条件和排序条件获取实体区间列表 97 | /// (查询使用表达式,排序使用表达式) 98 | /// 99 | /// 查询条件 100 | /// 起始行数 101 | /// 最大条数 102 | /// 排序方向 103 | /// 排序字段 104 | /// 实体区间列表 105 | public virtual IEnumerable GetSet(Expression> predicate, 106 | int firstResult, int maxResults, 107 | SortDirection ascending, 108 | params Expression>[] sortingExpression) 109 | { 110 | using (var connection = OpenConnection()) 111 | { 112 | var predicateGp = predicate.ToPredicateGroup(); 113 | var sort = sortingExpression.ToSortable(ascending); 114 | return Configuration.DalImplementor.GetSet( 115 | connection: connection, 116 | predicate: predicateGp, 117 | sort: sort, 118 | firstResult: firstResult, 119 | maxResults: maxResults, 120 | transaction: null, 121 | commandTimeout: null, 122 | buffered: Configuration.Buffered); 123 | } 124 | } 125 | } 126 | } 127 | -------------------------------------------------------------------------------- /src/DapperDal/DalBaseOfTEntity.Insert.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Linq.Expressions; 5 | using System.Text; 6 | 7 | namespace DapperDal 8 | { 9 | public partial class DalBase where TEntity : class 10 | { 11 | /// 12 | /// 插入指定实体 13 | /// 14 | /// 实体 15 | /// 实体主键 16 | public virtual TPrimaryKey Insert(TEntity entity) 17 | { 18 | using (var connection = OpenConnection()) 19 | { 20 | return Configuration.DalImplementor.Insert( 21 | connection: connection, 22 | entity: entity, 23 | transaction: null, 24 | commandTimeout: null); 25 | } 26 | } 27 | 28 | /// 29 | /// 批量插入指定实体集合 30 | /// 31 | /// 实体集合 32 | public virtual void Insert(IEnumerable entities) 33 | { 34 | using (var connection = OpenConnection()) 35 | { 36 | Configuration.DalImplementor.Insert( 37 | connection: connection, 38 | entities: entities, 39 | transaction: null, 40 | commandTimeout: null); 41 | } 42 | } 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /src/DapperDal/DalBaseOfTEntity.Query.OtherConn.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Data; 4 | using System.Linq; 5 | using System.Text; 6 | using Dapper; 7 | 8 | namespace DapperDal 9 | { 10 | public partial class DalBase where TEntity : class 11 | { 12 | /// 13 | /// 使用SQL语句获取实体集合 14 | /// 15 | /// DB 连接字符串配置节点名 16 | /// SQL语句 17 | /// 实体集合 18 | public virtual IEnumerable Query(string connNameOrConnStr, string sql) 19 | { 20 | using (var connection = OpenConnection(connNameOrConnStr)) 21 | { 22 | return connection.Query(sql); 23 | } 24 | } 25 | 26 | /// 27 | /// 使用SQL语句获取实体集合 28 | /// 29 | /// DB 连接字符串配置节点名 30 | /// SQL语句 31 | /// SQL参数 32 | /// 实体集合 33 | public virtual IEnumerable Query(string connNameOrConnStr, string sql, object parameters) 34 | { 35 | using (var connection = OpenConnection(connNameOrConnStr)) 36 | { 37 | return connection.Query(sql, parameters); 38 | } 39 | } 40 | 41 | /// 42 | /// 使用SQL语句获取实体集合 43 | /// 44 | /// DB 连接字符串配置节点名 45 | /// SQL语句 46 | /// SQL参数 47 | /// SQL语句命令类型 48 | /// 实体集合 49 | public virtual IEnumerable Query(string connNameOrConnStr, string sql, object parameters, CommandType commandType) 50 | { 51 | using (var connection = OpenConnection(connNameOrConnStr)) 52 | { 53 | return connection.Query(sql, parameters, commandType: commandType); 54 | } 55 | } 56 | 57 | /// 58 | /// 使用SQL语句获取指定实体集合 59 | /// 60 | /// 返回实体类型 61 | /// DB 连接字符串配置节点名 62 | /// SQL语句 63 | /// 实体集合 64 | public virtual IEnumerable Query(string connNameOrConnStr, string sql) 65 | { 66 | using (var connection = OpenConnection(connNameOrConnStr)) 67 | { 68 | return connection.Query(sql); 69 | } 70 | } 71 | 72 | /// 73 | /// 使用SQL语句获取指定实体集合 74 | /// 75 | /// 返回实体类型 76 | /// DB 连接字符串配置节点名 77 | /// SQL语句 78 | /// SQL参数 79 | /// 实体集合 80 | public virtual IEnumerable Query(string connNameOrConnStr, string sql, object parameters) 81 | { 82 | using (var connection = OpenConnection(connNameOrConnStr)) 83 | { 84 | return connection.Query(sql, parameters); 85 | } 86 | } 87 | 88 | /// 89 | /// 使用SQL语句获取指定实体集合 90 | /// 91 | /// 返回实体类型 92 | /// DB 连接字符串配置节点名 93 | /// SQL语句 94 | /// SQL参数 95 | /// SQL语句命令类型 96 | /// 实体集合 97 | public virtual IEnumerable Query(string connNameOrConnStr, string sql, object parameters, CommandType commandType) 98 | { 99 | using (var connection = OpenConnection(connNameOrConnStr)) 100 | { 101 | return connection.Query(sql, parameters, commandType: commandType); 102 | } 103 | } 104 | } 105 | } 106 | -------------------------------------------------------------------------------- /src/DapperDal/DalBaseOfTEntity.Query.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Data; 4 | using System.Linq; 5 | using System.Text; 6 | using Dapper; 7 | 8 | namespace DapperDal 9 | { 10 | public partial class DalBase where TEntity : class 11 | { 12 | /// 13 | /// 使用SQL语句获取实体集合 14 | /// 15 | /// SQL语句 16 | /// 实体集合 17 | public virtual IEnumerable Query(string sql) 18 | { 19 | using (var connection = OpenConnection()) 20 | { 21 | return connection.Query(sql); 22 | } 23 | } 24 | 25 | /// 26 | /// 使用SQL语句获取实体集合 27 | /// 28 | /// SQL语句 29 | /// SQL参数 30 | /// 实体集合 31 | public virtual IEnumerable Query(string sql, object parameters) 32 | { 33 | using (var connection = OpenConnection()) 34 | { 35 | return connection.Query(sql, parameters); 36 | } 37 | } 38 | 39 | /// 40 | /// 使用SQL语句获取实体集合 41 | /// 42 | /// SQL语句 43 | /// SQL参数 44 | /// SQL语句命令类型 45 | /// 实体集合 46 | public virtual IEnumerable Query(string sql, object parameters, CommandType commandType) 47 | { 48 | using (var connection = OpenConnection()) 49 | { 50 | return connection.Query(sql, parameters, commandType: commandType); 51 | } 52 | } 53 | 54 | /// 55 | /// 使用SQL语句获取指定实体集合 56 | /// 57 | /// 返回实体类型 58 | /// SQL语句 59 | /// 实体集合 60 | public virtual IEnumerable Query(string sql) 61 | { 62 | using (var connection = OpenConnection()) 63 | { 64 | return connection.Query(sql); 65 | } 66 | } 67 | 68 | /// 69 | /// 使用SQL语句获取指定实体集合 70 | /// 71 | /// 返回实体类型 72 | /// SQL语句 73 | /// SQL参数 74 | /// 实体集合 75 | public virtual IEnumerable Query(string sql, object parameters) 76 | { 77 | using (var connection = OpenConnection()) 78 | { 79 | return connection.Query(sql, parameters); 80 | } 81 | } 82 | 83 | /// 84 | /// 使用SQL语句获取指定实体集合 85 | /// 86 | /// 返回实体类型 87 | /// SQL语句 88 | /// SQL参数 89 | /// SQL语句命令类型 90 | /// 实体集合 91 | public virtual IEnumerable Query(string sql, object parameters, CommandType commandType) 92 | { 93 | using (var connection = OpenConnection()) 94 | { 95 | return connection.Query(sql, parameters, commandType: commandType); 96 | } 97 | } 98 | } 99 | } 100 | -------------------------------------------------------------------------------- /src/DapperDal/DalBaseOfTEntity.QueryDataSet.OtherConn.cs: -------------------------------------------------------------------------------- 1 | using System.Data; 2 | using Dapper; 3 | 4 | namespace DapperDal 5 | { 6 | public partial class DalBase where TEntity : class 7 | { 8 | /// 9 | /// 执行 SQL 语句返回 DataSet 10 | /// 11 | /// DB 连接字符串配置节点名 12 | /// SQL语句 13 | /// DataSet 14 | public virtual DataSet QueryDataSet(string connNameOrConnStr, string sql) 15 | { 16 | using (var connection = OpenConnection(connNameOrConnStr)) 17 | { 18 | using (var reader = connection.ExecuteReader(sql)) 19 | { 20 | DataSet ds = new DataSet(); 21 | 22 | while (!reader.IsClosed) 23 | { 24 | ds.Tables.Add().Load(reader); 25 | } 26 | 27 | return ds; 28 | } 29 | } 30 | } 31 | 32 | /// 33 | /// 执行 SQL 语句返回 DataSet 34 | /// 35 | /// DB 连接字符串配置节点名 36 | /// SQL语句 37 | /// SQL参数 38 | /// DataSet 39 | public virtual DataSet QueryDataSet(string connNameOrConnStr, string sql, object parameters) 40 | { 41 | using (var connection = OpenConnection(connNameOrConnStr)) 42 | { 43 | using (var reader = connection.ExecuteReader(sql, parameters)) 44 | { 45 | DataSet ds = new DataSet(); 46 | 47 | while (!reader.IsClosed) 48 | { 49 | ds.Tables.Add().Load(reader); 50 | } 51 | 52 | return ds; 53 | } 54 | } 55 | } 56 | 57 | /// 58 | /// 执行 SQL 语句返回 DataSet 59 | /// 60 | /// DB 连接字符串配置节点名 61 | /// SQL语句 62 | /// SQL参数 63 | /// SQL语句命令类型 64 | /// DataSet 65 | public virtual DataSet QueryDataSet(string connNameOrConnStr, string sql, object parameters, 66 | CommandType commandType) 67 | { 68 | using (var connection = OpenConnection(connNameOrConnStr)) 69 | { 70 | using (var reader = connection.ExecuteReader(sql, parameters, commandType: commandType)) 71 | { 72 | DataSet ds = new DataSet(); 73 | 74 | while (!reader.IsClosed) 75 | { 76 | ds.Tables.Add().Load(reader); 77 | } 78 | 79 | return ds; 80 | } 81 | } 82 | } 83 | } 84 | } 85 | -------------------------------------------------------------------------------- /src/DapperDal/DalBaseOfTEntity.QueryDataSet.cs: -------------------------------------------------------------------------------- 1 | using System.Data; 2 | using Dapper; 3 | 4 | namespace DapperDal 5 | { 6 | public partial class DalBase where TEntity : class 7 | { 8 | /// 9 | /// 执行 SQL 语句返回 DataSet 10 | /// 11 | /// SQL语句 12 | /// DataSet 13 | public virtual DataSet QueryDataSet(string sql) 14 | { 15 | using (var connection = OpenConnection()) 16 | { 17 | using (var reader = connection.ExecuteReader(sql)) 18 | { 19 | DataSet ds = new DataSet(); 20 | 21 | while (!reader.IsClosed) 22 | { 23 | ds.Tables.Add().Load(reader); 24 | } 25 | 26 | return ds; 27 | } 28 | } 29 | } 30 | 31 | /// 32 | /// 执行 SQL 语句返回 DataSet 33 | /// 34 | /// SQL语句 35 | /// SQL参数 36 | /// DataSet 37 | public virtual DataSet QueryDataSet(string sql, object parameters) 38 | { 39 | using (var connection = OpenConnection()) 40 | { 41 | using (var reader = connection.ExecuteReader(sql, parameters)) 42 | { 43 | DataSet ds = new DataSet(); 44 | 45 | while (!reader.IsClosed) 46 | { 47 | ds.Tables.Add().Load(reader); 48 | } 49 | 50 | return ds; 51 | } 52 | } 53 | } 54 | 55 | /// 56 | /// 执行 SQL 语句返回 DataSet 57 | /// 58 | /// SQL语句 59 | /// SQL参数 60 | /// SQL语句命令类型 61 | /// DataSet 62 | public virtual DataSet QueryDataSet(string sql, object parameters, CommandType commandType) 63 | { 64 | using (var connection = OpenConnection()) 65 | { 66 | using (var reader = connection.ExecuteReader(sql, parameters, commandType: commandType)) 67 | { 68 | DataSet ds = new DataSet(); 69 | 70 | while (!reader.IsClosed) 71 | { 72 | ds.Tables.Add().Load(reader); 73 | } 74 | 75 | return ds; 76 | } 77 | } 78 | } 79 | } 80 | } 81 | -------------------------------------------------------------------------------- /src/DapperDal/DalBaseOfTEntity.QueryFirst.OtherConn.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Data; 4 | using System.Linq; 5 | using System.Text; 6 | using Dapper; 7 | 8 | namespace DapperDal 9 | { 10 | public partial class DalBase where TEntity : class 11 | { 12 | /// 13 | /// 使用SQL语句获取实体 14 | /// 15 | /// DB 连接字符串配置节点名 16 | /// SQL语句 17 | /// 实体 18 | public virtual TEntity QueryFirst(string connNameOrConnStr, string sql) 19 | { 20 | using (var connection = OpenConnection(connNameOrConnStr)) 21 | { 22 | return connection.QueryFirstOrDefault(sql); 23 | } 24 | } 25 | 26 | /// 27 | /// 使用SQL语句获取实体 28 | /// 29 | /// DB 连接字符串配置节点名 30 | /// SQL语句 31 | /// SQL参数 32 | /// 实体 33 | public virtual TEntity QueryFirst(string connNameOrConnStr, string sql, object parameters) 34 | { 35 | using (var connection = OpenConnection(connNameOrConnStr)) 36 | { 37 | return connection.QueryFirstOrDefault(sql, parameters); 38 | } 39 | } 40 | 41 | /// 42 | /// 使用SQL语句获取实体 43 | /// 44 | /// DB 连接字符串配置节点名 45 | /// SQL语句 46 | /// SQL参数 47 | /// SQL语句命令类型 48 | /// 实体 49 | public virtual TEntity QueryFirst(string connNameOrConnStr, string sql, object parameters, CommandType commandType) 50 | { 51 | using (var connection = OpenConnection(connNameOrConnStr)) 52 | { 53 | return connection.QueryFirstOrDefault(sql, parameters, commandType: commandType); 54 | } 55 | } 56 | 57 | /// 58 | /// 使用SQL语句获取指定实体 59 | /// 60 | /// 返回实体类型 61 | /// DB 连接字符串配置节点名 62 | /// SQL语句 63 | /// 实体 64 | public virtual TAny QueryFirst(string connNameOrConnStr, string sql) 65 | { 66 | using (var connection = OpenConnection(connNameOrConnStr)) 67 | { 68 | return connection.QueryFirstOrDefault(sql); 69 | } 70 | } 71 | 72 | /// 73 | /// 使用SQL语句获取指定实体 74 | /// 75 | /// 返回实体类型 76 | /// DB 连接字符串配置节点名 77 | /// SQL语句 78 | /// SQL参数 79 | /// 实体 80 | public virtual TAny QueryFirst(string connNameOrConnStr, string sql, object parameters) 81 | { 82 | using (var connection = OpenConnection(connNameOrConnStr)) 83 | { 84 | return connection.QueryFirstOrDefault(sql, parameters); 85 | } 86 | } 87 | 88 | /// 89 | /// 使用SQL语句获取指定实体 90 | /// 91 | /// 返回实体类型 92 | /// DB 连接字符串配置节点名 93 | /// SQL语句 94 | /// SQL参数 95 | /// SQL语句命令类型 96 | /// 实体 97 | public virtual TAny QueryFirst(string connNameOrConnStr, string sql, object parameters, CommandType commandType) 98 | { 99 | using (var connection = OpenConnection(connNameOrConnStr)) 100 | { 101 | return connection.QueryFirstOrDefault(sql, parameters, commandType: commandType); 102 | } 103 | } 104 | } 105 | } 106 | -------------------------------------------------------------------------------- /src/DapperDal/DalBaseOfTEntity.QueryFirst.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Data; 4 | using System.Linq; 5 | using System.Text; 6 | using Dapper; 7 | 8 | namespace DapperDal 9 | { 10 | public partial class DalBase where TEntity : class 11 | { 12 | /// 13 | /// 使用SQL语句获取实体 14 | /// 15 | /// SQL语句 16 | /// 实体 17 | public virtual TEntity QueryFirst(string sql) 18 | { 19 | using (var connection = OpenConnection()) 20 | { 21 | return connection.QueryFirstOrDefault(sql); 22 | } 23 | } 24 | 25 | /// 26 | /// 使用SQL语句获取实体 27 | /// 28 | /// SQL语句 29 | /// SQL参数 30 | /// 实体 31 | public virtual TEntity QueryFirst(string sql, object parameters) 32 | { 33 | using (var connection = OpenConnection()) 34 | { 35 | return connection.QueryFirstOrDefault(sql, parameters); 36 | } 37 | } 38 | 39 | /// 40 | /// 使用SQL语句获取实体 41 | /// 42 | /// SQL语句 43 | /// SQL参数 44 | /// SQL语句命令类型 45 | /// 实体 46 | public virtual TEntity QueryFirst(string sql, object parameters, CommandType commandType) 47 | { 48 | using (var connection = OpenConnection()) 49 | { 50 | return connection.QueryFirstOrDefault(sql, parameters, commandType: commandType); 51 | } 52 | } 53 | 54 | /// 55 | /// 使用SQL语句获取指定实体 56 | /// 57 | /// 返回实体类型 58 | /// SQL语句 59 | /// 实体 60 | public virtual TAny QueryFirst(string sql) 61 | { 62 | using (var connection = OpenConnection()) 63 | { 64 | return connection.QueryFirstOrDefault(sql); 65 | } 66 | } 67 | 68 | /// 69 | /// 使用SQL语句获取指定实体 70 | /// 71 | /// 返回实体类型 72 | /// SQL语句 73 | /// SQL参数 74 | /// 实体 75 | public virtual TAny QueryFirst(string sql, object parameters) 76 | { 77 | using (var connection = OpenConnection()) 78 | { 79 | return connection.QueryFirstOrDefault(sql, parameters); 80 | } 81 | } 82 | 83 | /// 84 | /// 使用SQL语句获取指定实体 85 | /// 86 | /// 返回实体类型 87 | /// SQL语句 88 | /// SQL参数 89 | /// SQL语句命令类型 90 | /// 实体 91 | public virtual TAny QueryFirst(string sql, object parameters, CommandType commandType) 92 | { 93 | using (var connection = OpenConnection()) 94 | { 95 | return connection.QueryFirstOrDefault(sql, parameters, commandType: commandType); 96 | } 97 | } 98 | } 99 | } 100 | -------------------------------------------------------------------------------- /src/DapperDal/DalBaseOfTEntity.SoftDelete.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Linq.Expressions; 5 | using System.Text; 6 | 7 | namespace DapperDal 8 | { 9 | public partial class DalBase where TEntity : class 10 | { 11 | /// 12 | /// 逻辑删除指定实体 13 | /// 14 | /// 实体 15 | /// 逻辑删除属性名及更新值,默认 IsActive=0 16 | /// 逻辑删除结果 17 | public virtual bool SoftDelete(TEntity entity, object props = null) 18 | { 19 | return SwitchActive(entity, false, props); 20 | } 21 | 22 | /// 23 | /// 根据实体主键ID逻辑删除指定实体 24 | /// 25 | /// 实体主键ID 26 | /// 逻辑删除属性名及更新值,默认 IsActive=0 27 | /// 逻辑删除结果 28 | public virtual bool SoftDelete(TPrimaryKey id, object props = null) 29 | { 30 | return SwitchActive(id, false, props); 31 | } 32 | 33 | /// 34 | /// 根据条件逻辑删除实体 35 | /// 36 | /// 删除条件 37 | /// 逻辑删除属性名及更新值,默认 IsActive=0 38 | /// 逻辑删除结果 39 | public virtual bool SoftDelete(object predicate, object props = null) 40 | { 41 | return SwitchActive(predicate, false, props); 42 | } 43 | 44 | /// 45 | /// 根据条件逻辑删除实体 46 | /// 47 | /// 删除条件 48 | /// 逻辑删除属性名及更新值,默认 IsActive=0 } 49 | /// 逻辑删除结果 50 | public virtual bool SoftDelete(Expression> predicate, object props = null) 51 | { 52 | return SwitchActive(predicate, false, props); 53 | } 54 | 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /src/DapperDal/DalBaseOfTEntity.SwitchActive.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Linq.Expressions; 3 | using DapperDal.Expressions; 4 | using DapperDal.Predicate; 5 | 6 | namespace DapperDal 7 | { 8 | public partial class DalBase where TEntity : class 9 | { 10 | /// 11 | /// 逻辑删除或激活指定实体 12 | /// 13 | /// 实体 14 | /// 是否激活,true:激活,false:逻辑删除 15 | /// 逻辑删除属性名及更新值,默认:IsActive=0 16 | /// 激活属性名及更新值,默认:IsActive=1 17 | /// 更新结果 18 | public virtual bool SwitchActive(TEntity entity, bool isActive, 19 | object softDeleteProps = null, object softActiveProps = null) 20 | { 21 | if (isActive) 22 | { 23 | if (softActiveProps == null && Options.SoftActivePropsFactory != null) 24 | { 25 | softActiveProps = Options.SoftActivePropsFactory(); 26 | } 27 | 28 | return Update(entity, softActiveProps); 29 | } 30 | else 31 | { 32 | if (softDeleteProps == null && Options.SoftDeletePropsFactory != null) 33 | { 34 | softDeleteProps = Options.SoftDeletePropsFactory(); 35 | } 36 | 37 | return Update(entity, softDeleteProps); 38 | } 39 | } 40 | 41 | /// 42 | /// 根据实体主键ID逻辑删除或激活指定实体 43 | /// 44 | /// 实体主键ID 45 | /// 是否激活,true:激活,false:逻辑删除 46 | /// 逻辑删除属性名及更新值,默认:IsActive=0 47 | /// 激活属性名及更新值,默认:IsActive=1 48 | /// 更新结果 49 | public virtual bool SwitchActive(TPrimaryKey id, bool isActive, 50 | object softDeleteProps = null, object softActiveProps = null) 51 | { 52 | IPredicate predicate = Configuration.DalImplementor.GetIdPredicate(id); 53 | 54 | if (isActive) 55 | { 56 | if (softActiveProps == null && Options.SoftActivePropsFactory != null) 57 | { 58 | softActiveProps = Options.SoftActivePropsFactory(); 59 | } 60 | 61 | return Update(softActiveProps, predicate); 62 | } 63 | else 64 | { 65 | if (softDeleteProps == null && Options.SoftDeletePropsFactory != null) 66 | { 67 | softDeleteProps = Options.SoftDeletePropsFactory(); 68 | } 69 | 70 | return Update(softDeleteProps, predicate); 71 | } 72 | } 73 | 74 | /// 75 | /// 根据条件逻辑删除或激活实体 76 | /// 77 | /// 删除条件 78 | /// 是否激活,true:激活,false:逻辑删除 79 | /// 逻辑删除属性名及更新值,默认:IsActive=0 80 | /// 激活属性名及更新值,默认:IsActive=1 81 | /// 更新结果 82 | public virtual bool SwitchActive(object predicate, bool isActive, 83 | object softDeleteProps = null, object softActiveProps = null) 84 | { 85 | if (isActive) 86 | { 87 | if (softActiveProps == null && Options.SoftActivePropsFactory != null) 88 | { 89 | softActiveProps = Options.SoftActivePropsFactory(); 90 | } 91 | 92 | return Update(softActiveProps, predicate); 93 | } 94 | else 95 | { 96 | if (softDeleteProps == null && Options.SoftDeletePropsFactory != null) 97 | { 98 | softDeleteProps = Options.SoftDeletePropsFactory(); 99 | } 100 | 101 | return Update(softDeleteProps, predicate); 102 | } 103 | } 104 | 105 | /// 106 | /// 根据条件逻辑删除或激活实体 107 | /// 108 | /// 删除条件 109 | /// 是否激活,true:激活,false:逻辑删除 110 | /// 逻辑删除属性名及更新值,默认:IsActive=0 111 | /// 激活属性名及更新值,默认:IsActive=1 112 | /// 更新结果 113 | public virtual bool SwitchActive(Expression> predicate, bool isActive, 114 | object softDeleteProps = null, object softActiveProps = null) 115 | { 116 | if (isActive) 117 | { 118 | if (softActiveProps == null && Options.SoftActivePropsFactory != null) 119 | { 120 | softActiveProps = Options.SoftActivePropsFactory(); 121 | } 122 | 123 | var predicateGp = predicate.ToPredicateGroup(); 124 | return Update(softActiveProps, predicateGp); 125 | } 126 | else 127 | { 128 | if (softDeleteProps == null && Options.SoftDeletePropsFactory != null) 129 | { 130 | softDeleteProps = Options.SoftDeletePropsFactory(); 131 | } 132 | 133 | var predicateGp = predicate.ToPredicateGroup(); 134 | return Update(softDeleteProps, predicateGp); 135 | } 136 | } 137 | } 138 | } 139 | -------------------------------------------------------------------------------- /src/DapperDal/DalBaseOfTEntity.Update.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Linq.Expressions; 5 | using DapperDal.Expressions; 6 | using DapperDal.Predicate; 7 | 8 | namespace DapperDal 9 | { 10 | public partial class DalBase where TEntity : class 11 | { 12 | /// 13 | /// 更新指定实体 14 | /// 15 | /// 实体 16 | /// 更新结果 17 | public virtual bool Update(TEntity entity) 18 | { 19 | using (var connection = OpenConnection()) 20 | { 21 | return Configuration.DalImplementor.Update( 22 | connection: connection, 23 | entity: entity, 24 | transaction: null, 25 | commandTimeout: null); 26 | } 27 | } 28 | 29 | /// 30 | /// 更新指定实体指定属性 31 | /// 32 | /// 实体 33 | /// 要更新的属性名列表 34 | /// 更新结果 35 | public virtual bool Update(TEntity entity, IEnumerable props) 36 | { 37 | using (var connection = OpenConnection()) 38 | { 39 | return Configuration.DalImplementor.Update( 40 | connection: connection, 41 | entity: entity, 42 | props: props.ToList(), 43 | transaction: null, 44 | commandTimeout: null); 45 | } 46 | } 47 | 48 | /// 49 | /// 更新指定实体指定属性 50 | /// 51 | /// 实体 52 | /// 要更新的属性名列表,以匿名对象提供 53 | /// 更新结果 54 | public virtual bool Update(TEntity entity, object props) 55 | { 56 | using (var connection = OpenConnection()) 57 | { 58 | return Configuration.DalImplementor.Update( 59 | connection: connection, 60 | entity: entity, 61 | props: props, 62 | transaction: null, 63 | commandTimeout: null); 64 | } 65 | } 66 | 67 | /// 68 | /// 更新指定实体指定属性 69 | /// 70 | /// 实体主键ID 71 | /// 更新属性名 72 | /// 更新结果 73 | public virtual bool Update(TPrimaryKey id, object props) 74 | { 75 | using (var connection = OpenConnection()) 76 | { 77 | IPredicate predicate = Configuration.DalImplementor.GetIdPredicate(id); 78 | 79 | return Configuration.DalImplementor.Update( 80 | connection: connection, 81 | props: props, 82 | predicate: predicate, 83 | transaction: null, 84 | commandTimeout: null); 85 | } 86 | } 87 | 88 | /// 89 | /// 根据指定指定主键ID更新实体指定属性 90 | /// (条件使用实体主键ID) 91 | /// 92 | /// 更新实体,包含主键ID、更新属性及值 93 | /// 更新结果 94 | public virtual bool Update(object keyAndProps) 95 | { 96 | using (var connection = OpenConnection()) 97 | { 98 | return Configuration.DalImplementor.Update( 99 | connection: connection, 100 | keyAndProps: keyAndProps, 101 | transaction: null, 102 | commandTimeout: null); 103 | } 104 | } 105 | 106 | /// 107 | /// 根据指定更新条件更新实体指定属性 108 | /// (条件使用谓词或匿名对象) 109 | /// 110 | /// 更新属性及值 111 | /// 更新条件,使用谓词或匿名对象 112 | /// 更新结果 113 | public virtual bool Update(object props, object predicate) 114 | { 115 | using (var connection = OpenConnection()) 116 | { 117 | return Configuration.DalImplementor.Update( 118 | connection: connection, 119 | props: props, 120 | predicate: predicate, 121 | transaction: null, 122 | commandTimeout: null); 123 | } 124 | } 125 | 126 | /// 127 | /// 根据指定更新条件更新实体指定属性 128 | /// (条件使用表达式) 129 | /// 130 | /// 更新属性及值 131 | /// 更新条件,使用表达式 132 | /// 更新结果 133 | public virtual bool Update(object props, Expression> predicate) 134 | { 135 | using (var connection = OpenConnection()) 136 | { 137 | var predicateGp = predicate.ToPredicateGroup(); 138 | 139 | return Configuration.DalImplementor.Update( 140 | connection: connection, 141 | props: props, 142 | predicate: predicateGp, 143 | transaction: null, 144 | commandTimeout: null); 145 | } 146 | } 147 | } 148 | } 149 | -------------------------------------------------------------------------------- /src/DapperDal/DalBaseOfTEntity.cs: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/arbing/DapperDal/bdb0beb99f3479e385bbad9970bbc4dda18ab925/src/DapperDal/DalBaseOfTEntity.cs -------------------------------------------------------------------------------- /src/DapperDal/DalConfiguration.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Concurrent; 3 | using System.Collections.Generic; 4 | using System.Linq; 5 | using System.Reflection; 6 | using DapperDal.Implementor; 7 | using DapperDal.Mapper; 8 | using DapperDal.Sql; 9 | 10 | namespace DapperDal 11 | { 12 | /// 13 | /// 数据访问配置接口 14 | /// 15 | public interface IDalConfiguration 16 | { 17 | /// 18 | /// 默认实体映射类型 19 | /// 20 | Type DefaultMapper { get; set; } 21 | 22 | /// 23 | /// 实体映射类型检索程序集 24 | /// 25 | IList MappingAssemblies { get; set; } 26 | 27 | /// 28 | /// SQL方言实例 29 | /// 30 | ISqlDialect Dialect { get; set; } 31 | 32 | /// 33 | /// 数据访问实现实例 34 | /// 35 | IDalImplementor DalImplementor { get; set; } 36 | 37 | /// 38 | /// 生成SQL时,是否添加 WITH (NOLOCK) 39 | /// 40 | bool Nolock { get; set; } 41 | 42 | /// 43 | /// SQL输出方法 44 | /// 45 | Action OutputSql { get; set; } 46 | 47 | /// 48 | /// 实体集合返回前是否要缓冲(ToList) 49 | /// 50 | bool Buffered { get; set; } 51 | 52 | /// 53 | /// 设置实体映射类型检索程序集 54 | /// 55 | /// 实体映射类型检索程序集 56 | void SetMappingAssemblies(IList assemblies); 57 | 58 | /// 59 | /// 获取实体映射类型 60 | /// 61 | /// 实体类型 62 | /// 实体映射类型 63 | IClassMapper GetMap(Type entityType); 64 | 65 | /// 66 | /// 获取实体映射类型 67 | /// 68 | /// 实体类型 69 | /// 实体映射类型 70 | IClassMapper GetMap() where T : class; 71 | 72 | /// 73 | /// 清空实体映射类型缓存 74 | /// 75 | void ClearCache(); 76 | 77 | /// 78 | /// 获取新的GUID 79 | /// 80 | /// 新的GUID 81 | Guid GetNextGuid(); 82 | } 83 | 84 | /// 85 | /// 数据访问配置类 86 | /// 87 | public class DalConfiguration : IDalConfiguration 88 | { 89 | private readonly ConcurrentDictionary _classMaps = new ConcurrentDictionary(); 90 | 91 | static DalConfiguration() 92 | { 93 | Default = new DalConfiguration(); 94 | } 95 | 96 | /// 97 | /// 初始化数据访问配置 98 | /// 99 | public DalConfiguration() 100 | : this(typeof(AutoClassMapper<>), new List(), new SqlServerDialect()) 101 | { 102 | } 103 | 104 | 105 | /// 106 | /// 初始化数据访问配置 107 | /// 108 | /// 默认实体映射类型 109 | /// 实体映射类型检索程序集 110 | /// SQL方言实例 111 | public DalConfiguration(Type defaultMapper, IList mappingAssemblies, ISqlDialect sqlDialect) 112 | { 113 | DefaultMapper = defaultMapper; 114 | MappingAssemblies = mappingAssemblies ?? new List(); 115 | Dialect = sqlDialect; 116 | DalImplementor = new DalImplementor(new SqlGeneratorImpl(this)); 117 | } 118 | 119 | /// 120 | /// 全局默认配置 121 | /// 122 | public static IDalConfiguration Default { get; } 123 | 124 | /// 125 | public Type DefaultMapper { get; set; } 126 | 127 | /// 128 | public IList MappingAssemblies { get; set; } 129 | 130 | /// 131 | public ISqlDialect Dialect { get; set; } 132 | 133 | /// 134 | public IDalImplementor DalImplementor { get; set; } 135 | 136 | /// 137 | /// 生成SQL时,是否添加 WITH (NOLOCK) 138 | /// 139 | public bool Nolock { get; set; } 140 | 141 | /// 142 | /// SQL输出方法 143 | /// 144 | public Action OutputSql { get; set; } 145 | 146 | /// 147 | /// 实体集合返回前是否要缓冲(ToList) 148 | /// 149 | public bool Buffered { get; set; } 150 | 151 | /// 152 | public void SetMappingAssemblies(IList assemblies) 153 | { 154 | MappingAssemblies = assemblies ?? new List(); 155 | ClearCache(); 156 | DalImplementor = new DalImplementor(new SqlGeneratorImpl(this)); 157 | } 158 | 159 | /// 160 | public IClassMapper GetMap(Type entityType) 161 | { 162 | IClassMapper map; 163 | if (!_classMaps.TryGetValue(entityType, out map)) 164 | { 165 | Type mapType = GetMapType(entityType); 166 | if (mapType == null) 167 | { 168 | mapType = DefaultMapper.MakeGenericType(entityType); 169 | } 170 | 171 | map = Activator.CreateInstance(mapType) as IClassMapper; 172 | _classMaps[entityType] = map; 173 | } 174 | 175 | return map; 176 | } 177 | 178 | /// 179 | public IClassMapper GetMap() where T : class 180 | { 181 | return GetMap(typeof(T)); 182 | } 183 | 184 | /// 185 | public void ClearCache() 186 | { 187 | _classMaps.Clear(); 188 | } 189 | 190 | /// 191 | public Guid GetNextGuid() 192 | { 193 | byte[] b = Guid.NewGuid().ToByteArray(); 194 | DateTime dateTime = new DateTime(1900, 1, 1); 195 | DateTime now = DateTime.Now; 196 | TimeSpan timeSpan = new TimeSpan(now.Ticks - dateTime.Ticks); 197 | TimeSpan timeOfDay = now.TimeOfDay; 198 | byte[] bytes1 = BitConverter.GetBytes(timeSpan.Days); 199 | byte[] bytes2 = BitConverter.GetBytes((long)(timeOfDay.TotalMilliseconds / 3.333333)); 200 | Array.Reverse(bytes1); 201 | Array.Reverse(bytes2); 202 | Array.Copy(bytes1, bytes1.Length - 2, b, b.Length - 6, 2); 203 | Array.Copy(bytes2, bytes2.Length - 4, b, b.Length - 4, 4); 204 | return new Guid(b); 205 | } 206 | 207 | private Type GetMapType(Type entityType) 208 | { 209 | Func getType = a => 210 | { 211 | Type[] types = a.GetTypes(); 212 | return (from type in types 213 | let interfaceType = type.GetInterface(typeof(IClassMapper<>).FullName) 214 | where 215 | interfaceType != null && 216 | interfaceType.GetGenericArguments()[0] == entityType 217 | select type).SingleOrDefault(); 218 | }; 219 | 220 | Type result = getType(entityType.Assembly); 221 | if (result != null) 222 | { 223 | return result; 224 | } 225 | 226 | foreach (var mappingAssembly in MappingAssemblies) 227 | { 228 | result = getType(mappingAssembly); 229 | if (result != null) 230 | { 231 | return result; 232 | } 233 | } 234 | 235 | return getType(entityType.Assembly); 236 | } 237 | } 238 | } -------------------------------------------------------------------------------- /src/DapperDal/DalOptions.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace DapperDal 4 | { 5 | /// 6 | /// 数据访问设置项 7 | /// 8 | public class DalOptions 9 | { 10 | /// 11 | /// 逻辑删除时更新属性和值的构造器 12 | /// 13 | public Func SoftDeletePropsFactory { get; set; } 14 | 15 | /// 16 | /// 逻辑激活时更新属性和值的构造器 17 | /// 18 | public Func SoftActivePropsFactory { get; set; } 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/DapperDal/DapperDal.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | Debug 5 | AnyCPU 6 | {64CCA848-7660-43EE-ABAE-91EFFE765E41} 7 | Library 8 | Properties 9 | DapperDal 10 | DapperDal 11 | v4.0 12 | 512 13 | true 14 | 15 | 16 | true 17 | full 18 | false 19 | bin\Debug\ 20 | DEBUG;TRACE 21 | prompt 22 | 4 23 | bin\Debug\DapperDal.xml 24 | 25 | 26 | pdbonly 27 | true 28 | bin\Release\ 29 | TRACE 30 | prompt 31 | 4 32 | bin\Release\DapperDal.xml 33 | 34 | 35 | 36 | ..\..\packages\Dapper.1.50.2\lib\net40\Dapper.dll 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 113 | -------------------------------------------------------------------------------- /src/DapperDal/Expressions/ExpressionUtility.cs: -------------------------------------------------------------------------------- 1 | // https://github.com/alexfoxgill/ExpressionTools 2 | 3 | using System; 4 | using System.Collections.Generic; 5 | using System.Linq.Expressions; 6 | using System.Reflection; 7 | 8 | namespace DapperDal.Expressions 9 | { 10 | /// 11 | /// 表达式工具方法 12 | /// 13 | internal static class ExpressionUtility 14 | { 15 | /// 16 | /// 判断表达式是否是常量表达式 17 | /// 18 | /// 表达式参数类型 19 | /// 表达式返回类型 20 | /// 要判断的表达式 21 | /// 常量 22 | /// 判断结果 23 | public static bool IsConstant(Expression> expr, TResult value) 24 | { 25 | var constant = expr.Body as ConstantExpression; 26 | if (constant == null) 27 | return false; 28 | return constant.Value.Equals(value); 29 | } 30 | 31 | /// 32 | /// 从属性表达式获取属性元数据访问实例 33 | /// 34 | /// 属性表达式参数类型 35 | /// 属性表达式返回类型 36 | /// 属性表达式 37 | /// 属性元数据访问实例 38 | public static PropertyInfo GetPropertyInfo(this Expression> propertyGetter) 39 | { 40 | var memberExpr = propertyGetter.Body as MemberExpression; 41 | if (memberExpr == null) 42 | throw new ArgumentException("Expression should be property getter: " + propertyGetter); 43 | var propInfo = memberExpr.Member as PropertyInfo; 44 | if (propInfo == null) 45 | throw new ArgumentException("Expression should be property getter: " + propertyGetter); 46 | return propInfo; 47 | } 48 | 49 | /// 50 | /// 51 | /// 52 | /// 53 | /// 54 | /// 55 | public static MemberInitExpression AddBinding(this MemberInitExpression memberInit, MemberBinding binding) 56 | { 57 | var bindings = new List(memberInit.Bindings) 58 | { 59 | binding 60 | }; 61 | return Expression.MemberInit(memberInit.NewExpression, bindings); 62 | } 63 | 64 | /// 65 | /// 66 | /// 67 | /// 68 | /// 69 | /// 70 | /// 71 | public static Expression Replace(this Expression expression, Expression toReplace, Expression replacement) 72 | { 73 | return ExpressionReplacer.Replace(expression, toReplace.Equals, x => replacement); 74 | } 75 | 76 | public static Expression Replace(this Expression expression, IDictionary map) 77 | { 78 | return ExpressionReplacer.Replace(expression, map.ContainsKey, x => map[x]); 79 | } 80 | 81 | class ExpressionReplacer : ExpressionVisitor 82 | { 83 | private readonly Func _match; 84 | private readonly Func _replace; 85 | 86 | private ExpressionReplacer(Func match, Func replace) 87 | { 88 | _match = match; 89 | _replace = replace; 90 | } 91 | 92 | public override Expression Visit(Expression node) 93 | { 94 | return _match(node) ? _replace(node) : base.Visit(node); 95 | } 96 | 97 | public static Expression Replace(Expression expression, Func match, 98 | Func replace) 99 | { 100 | return new ExpressionReplacer(match, replace).Visit(expression); 101 | } 102 | } 103 | } 104 | } -------------------------------------------------------------------------------- /src/DapperDal/Expressions/PredicateBuilder.cs: -------------------------------------------------------------------------------- 1 | // https://github.com/alexfoxgill/ExpressionTools 2 | 3 | using System; 4 | using System.Collections.Generic; 5 | using System.Linq; 6 | using System.Linq.Expressions; 7 | using DapperDal.Utils; 8 | 9 | namespace DapperDal.Expressions 10 | { 11 | /// 12 | /// 谓词表达式构建扩展方法 13 | /// 14 | public static class PredicateBuilder 15 | { 16 | /// 17 | /// Produces a predicate expression always returning true 18 | /// 19 | /// The input type for the resulting expression 20 | /// A constant expression returning true 21 | public static Expression> True() 22 | { 23 | return _ => true; 24 | } 25 | 26 | /// 27 | /// Produces a predicate expression always returning false 28 | /// 29 | /// The input type for the resulting expression 30 | /// A constant expression returning false 31 | public static Expression> False() 32 | { 33 | return _ => false; 34 | } 35 | 36 | /// 37 | /// Combines the first predicate with the second using a logical "and". Short-circuits if either expression is constant 38 | /// 39 | /// The input type for both predicates 40 | /// The first predicate 41 | /// The second predicate 42 | /// An expression representing a logical "and" between both predicates 43 | public static Expression> And(this Expression> first, 44 | Expression> second) 45 | { 46 | if (ExpressionUtility.IsConstant(first, true)) 47 | return second; 48 | if (ExpressionUtility.IsConstant(second, true)) 49 | return first; 50 | if (ExpressionUtility.IsConstant(first, false) || ExpressionUtility.IsConstant(second, false)) 51 | return False(); 52 | return first.Combine(second, (a, b) => a && b); 53 | } 54 | 55 | /// 56 | /// Combines the first predicate with the second using a logical "or". Short-circuits if either expression is constant 57 | /// 58 | /// The input type for both predicates 59 | /// The first predicate 60 | /// The second predicate 61 | /// An expression representing a logical "or" between both predicates 62 | public static Expression> Or(this Expression> first, 63 | Expression> second) 64 | { 65 | if (ExpressionUtility.IsConstant(first, false)) 66 | return second; 67 | if (ExpressionUtility.IsConstant(second, false)) 68 | return first; 69 | if (ExpressionUtility.IsConstant(first, true) || ExpressionUtility.IsConstant(second, true)) 70 | return True(); 71 | return first.Combine(second, (a, b) => a || b); 72 | } 73 | 74 | /// 75 | /// Composes a negation with the result of the predicate 76 | /// 77 | /// The input type for the predicate 78 | /// The predicate 79 | /// An expression negating the result of the predicate 80 | public static Expression> Not(this Expression> expr) 81 | { 82 | return expr.Compose(x => !x); 83 | } 84 | 85 | /// 86 | /// Performs a reduction on the given list of predicates using logical "and". Returns a expression if the list is empty 87 | /// 88 | /// The input type for all predicates 89 | /// The predicates 90 | /// A series of "and" expressions 91 | public static Expression> All(this IEnumerable>> predicates) 92 | { 93 | return predicates.Aggregate(True(), And); 94 | } 95 | 96 | /// 97 | /// Performs a reduction on the given list of predicates using logical "and". Returns a expression if the list is empty 98 | /// 99 | /// The input type for all predicates 100 | /// The predicates 101 | /// A series of "and" expressions 102 | public static Expression> All(params Expression>[] predicates) 103 | { 104 | return All(predicates.AsEnumerable()); 105 | } 106 | 107 | /// 108 | /// Performs a reduction on the given list of predicates using logical "or". Returns a expression if the list is empty 109 | /// 110 | /// The input type for all predicates 111 | /// The predicates 112 | /// A series of "or" expressions 113 | public static Expression> Any(this IEnumerable>> predicates) 114 | { 115 | return predicates.Aggregate(False(), Or); 116 | } 117 | 118 | /// 119 | /// Performs a reduction on the given list of predicates using logical "or". Returns a expression if the list is empty 120 | /// 121 | /// The input type for all predicates 122 | /// The predicates 123 | /// A series of "or" expressions 124 | public static Expression> Any(params Expression>[] predicates) 125 | { 126 | return Any(predicates.AsEnumerable()); 127 | } 128 | } 129 | } -------------------------------------------------------------------------------- /src/DapperDal/Expressions/PredicateExtensions.cs: -------------------------------------------------------------------------------- 1 | // https://github.com/alexfoxgill/ExpressionTools 2 | 3 | using System; 4 | using System.Linq.Expressions; 5 | using DapperDal.Predicate; 6 | 7 | namespace DapperDal.Expressions 8 | { 9 | /// 10 | /// 查询条件表达式转换扩展 11 | /// 12 | public static class PredicateExtensions 13 | { 14 | /// 15 | /// 查询条件表达式转换为谓词组的扩展方法 16 | /// 17 | /// 实体类型 18 | /// 实体主键类型 19 | /// 查询条件表达式 20 | /// 查询条件谓词组 21 | public static IPredicate ToPredicateGroup( 22 | this Expression> expression) where TEntity : class 23 | { 24 | if (expression == null) 25 | { 26 | return null; 27 | } 28 | 29 | if (ExpressionUtility.IsConstant(expression, true)) 30 | { 31 | return null; 32 | } 33 | 34 | if (ExpressionUtility.IsConstant(expression, false)) 35 | { 36 | return null; 37 | } 38 | 39 | IPredicate pg = QueryBuilder.FromExpression(expression); 40 | 41 | return pg; 42 | } 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /src/DapperDal/Expressions/QueryFunctions.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace DapperDal.Expressions 4 | { 5 | /// 6 | /// 映射SQL查询支持的函数 7 | /// 8 | public static class QueryFunctions 9 | { 10 | /// 11 | /// For reflection only. 12 | /// 13 | /// 14 | /// 15 | /// 16 | public static bool Like(string pattern, object member) 17 | { 18 | throw new InvalidOperationException("For reflection only!"); 19 | } 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/DapperDal/Expressions/SortDirection.cs: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/arbing/DapperDal/bdb0beb99f3479e385bbad9970bbc4dda18ab925/src/DapperDal/Expressions/SortDirection.cs -------------------------------------------------------------------------------- /src/DapperDal/Expressions/SortingExtensions.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Linq.Expressions; 5 | using System.Reflection; 6 | using DapperDal.Predicate; 7 | using DapperDal.Utils; 8 | 9 | namespace DapperDal.Expressions 10 | { 11 | /// 12 | /// 排序条件转换扩展 13 | /// 14 | public static class SortingExtensions 15 | { 16 | /// 17 | /// 排序条件表达式转换为排序组的扩展方法 18 | /// 19 | /// 实体类型 20 | /// 排序条件表达式 21 | /// 排序方向 22 | /// 排序组 23 | public static IList ToSortable(this Expression>[] sortingExpression, 24 | SortDirection ascending = SortDirection.Ascending) 25 | { 26 | if (sortingExpression == null) 27 | { 28 | return null; 29 | } 30 | 31 | var sortList = new List(); 32 | sortingExpression.ToList().ForEach(sortExpression => 33 | { 34 | MemberInfo sortProperty = ReflectionHelper.GetProperty(sortExpression); 35 | sortList.Add(new Sort 36 | { 37 | Ascending = ascending != SortDirection.Descending, 38 | PropertyName = sortProperty.Name 39 | }); 40 | }); 41 | 42 | return sortList; 43 | } 44 | 45 | /// 46 | /// 匿名排序对象转换为排序组的扩展方法 47 | /// 48 | /// 匿名排序对象,如new { CarId = SortDirection.Descending } 49 | /// 排序组 50 | public static IList ToSortable(this object sort) 51 | { 52 | if (sort == null) 53 | { 54 | return null; 55 | } 56 | 57 | var isortList = sort as IList; 58 | if (isortList != null) 59 | { 60 | return isortList; 61 | } 62 | 63 | var sortList = sort as IList; 64 | if (sortList != null) 65 | { 66 | return new List(sortList); 67 | } 68 | 69 | var sorts = new List(); 70 | foreach (var kvp in ReflectionHelper.GetObjectValues(sort)) 71 | { 72 | var ascending = true; 73 | 74 | if (false.Equals(kvp.Value)) 75 | { 76 | ascending = false; 77 | } 78 | 79 | if (SortDirection.Descending.Equals(kvp.Value)) 80 | { 81 | ascending = false; 82 | } 83 | 84 | sorts.Add(new Sort { PropertyName = kvp.Key, Ascending = ascending }); 85 | } 86 | 87 | return sorts; 88 | } 89 | 90 | } 91 | } 92 | -------------------------------------------------------------------------------- /src/DapperDal/Mapper/AutoClassMapper.cs: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/arbing/DapperDal/bdb0beb99f3479e385bbad9970bbc4dda18ab925/src/DapperDal/Mapper/AutoClassMapper.cs -------------------------------------------------------------------------------- /src/DapperDal/Mapper/AutoEntityMapper.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace DapperDal.Mapper 4 | { 5 | /// 6 | /// 实体自动映射器类 7 | /// 8 | /// 实体类 9 | public class AutoEntityMapper : ClassMapper where T : class 10 | { 11 | /// 12 | /// 初始化自动映射实体 13 | /// 14 | public AutoEntityMapper() 15 | { 16 | Type type = typeof(T); 17 | Table(RemovePostFix(type.Name, "Entity")); 18 | AutoMap(); 19 | } 20 | 21 | 22 | /// 23 | /// Removes first occurrence of the given postfixes from end of the given string. 24 | /// 25 | /// The string. 26 | /// one or more postfix. 27 | /// Modified string or the same string if it has not any of given postfixes 28 | public static string RemovePostFix(string str, params string[] postFixes) 29 | { 30 | if (string.IsNullOrEmpty(str)) 31 | { 32 | return null; 33 | } 34 | 35 | if (postFixes == null || postFixes.Length == 0) 36 | { 37 | return str; 38 | } 39 | 40 | foreach (var postFix in postFixes) 41 | { 42 | if (!string.IsNullOrEmpty(postFix) && str.EndsWith(postFix)) 43 | { 44 | return str.Substring(0, str.Length - postFix.Length); 45 | } 46 | } 47 | 48 | return str; 49 | } 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /src/DapperDal/Mapper/ClassMapper.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Globalization; 4 | using System.Linq; 5 | using System.Linq.Expressions; 6 | using System.Numerics; 7 | using System.Reflection; 8 | using DapperDal.Utils; 9 | 10 | namespace DapperDal.Mapper 11 | { 12 | /// 13 | /// 实体类型映射器接口 14 | /// 15 | public interface IClassMapper 16 | { 17 | /// 18 | /// 数据库架构名 19 | /// 20 | string SchemaName { get; } 21 | 22 | /// 23 | /// 数据库表名 24 | /// 25 | string TableName { get; } 26 | 27 | /// 28 | /// 实体属性信息列表 29 | /// 30 | IList Properties { get; } 31 | 32 | /// 33 | /// 实体类型 34 | /// 35 | Type EntityType { get; } 36 | } 37 | 38 | /// 39 | /// 泛型实体映射器接口 40 | /// 41 | /// 实体类型 42 | public interface IClassMapper : IClassMapper where T : class 43 | { 44 | } 45 | 46 | /// 47 | /// 默认泛型实体映射器类 48 | /// 49 | public class ClassMapper : IClassMapper where T : class 50 | { 51 | /// 52 | public string SchemaName { get; protected set; } 53 | 54 | /// 55 | public string TableName { get; protected set; } 56 | 57 | /// 58 | public IList Properties { get; private set; } 59 | 60 | /// 61 | public Type EntityType 62 | { 63 | get { return typeof(T); } 64 | } 65 | 66 | /// 67 | /// 初始化默认泛型实体映射器 68 | /// 69 | public ClassMapper() 70 | { 71 | PropertyTypeKeyTypeMapping = new Dictionary 72 | { 73 | { typeof(byte), KeyType.Identity }, { typeof(byte?), KeyType.Identity }, 74 | { typeof(sbyte), KeyType.Identity }, { typeof(sbyte?), KeyType.Identity }, 75 | { typeof(short), KeyType.Identity }, { typeof(short?), KeyType.Identity }, 76 | { typeof(ushort), KeyType.Identity }, { typeof(ushort?), KeyType.Identity }, 77 | { typeof(int), KeyType.Identity }, { typeof(int?), KeyType.Identity }, 78 | { typeof(uint), KeyType.Identity}, { typeof(uint?), KeyType.Identity }, 79 | { typeof(long), KeyType.Identity }, { typeof(long?), KeyType.Identity }, 80 | { typeof(ulong), KeyType.Identity }, { typeof(ulong?), KeyType.Identity }, 81 | { typeof(BigInteger), KeyType.Identity }, { typeof(BigInteger?), KeyType.Identity }, 82 | { typeof(Guid), KeyType.Guid }, { typeof(Guid?), KeyType.Guid }, 83 | }; 84 | 85 | Properties = new List(); 86 | Table(typeof(T).Name); 87 | } 88 | 89 | /// 90 | /// 属性类型与键类型的对应关系字典 91 | /// 92 | protected Dictionary PropertyTypeKeyTypeMapping { get; private set; } 93 | 94 | /// 95 | /// 设置数据库架构名 96 | /// 97 | /// 数据库架构名 98 | public virtual void Schema(string schemaName) 99 | { 100 | SchemaName = schemaName; 101 | } 102 | 103 | /// 104 | /// 设置数据库表名 105 | /// 106 | /// 设置数据库表名 107 | public virtual void Table(string tableName) 108 | { 109 | TableName = tableName; 110 | } 111 | 112 | /// 113 | /// 执行自动映射 114 | /// 115 | protected virtual void AutoMap() 116 | { 117 | AutoMap(null); 118 | } 119 | 120 | /// 121 | /// 执行自动映射 122 | /// 123 | /// 指示实体属性是否要映射的方法提供 124 | protected virtual void AutoMap(Func canMap) 125 | { 126 | Type type = typeof(T); 127 | bool hasDefinedKey = Properties.Any(p => p.KeyType != KeyType.NotAKey); 128 | PropertyMap keyMap = null; 129 | foreach (var propertyInfo in type.GetProperties()) 130 | { 131 | if (Properties.Any(p => p.Name.Equals(propertyInfo.Name, StringComparison.InvariantCultureIgnoreCase))) 132 | { 133 | continue; 134 | } 135 | 136 | if ((canMap != null && !canMap(type, propertyInfo))) 137 | { 138 | continue; 139 | } 140 | 141 | PropertyMap map = Map(propertyInfo); 142 | if (!hasDefinedKey) 143 | { 144 | if (string.Equals(map.PropertyInfo.Name, "id", StringComparison.InvariantCultureIgnoreCase)) 145 | { 146 | keyMap = map; 147 | } 148 | 149 | if (keyMap == null && map.PropertyInfo.Name.EndsWith("id", true, CultureInfo.InvariantCulture)) 150 | { 151 | keyMap = map; 152 | } 153 | } 154 | } 155 | 156 | if (keyMap != null) 157 | { 158 | keyMap.Key(PropertyTypeKeyTypeMapping.ContainsKey(keyMap.PropertyInfo.PropertyType) 159 | ? PropertyTypeKeyTypeMapping[keyMap.PropertyInfo.PropertyType] 160 | : KeyType.Assigned); 161 | } 162 | } 163 | 164 | /// 165 | /// 设置实体属性映射,支持链式调用 166 | /// 167 | /// 实体属性映射表达式 168 | /// 实体属性映射器 169 | protected PropertyMap Map(Expression> expression) 170 | { 171 | PropertyInfo propertyInfo = ReflectionHelper.GetProperty(expression) as PropertyInfo; 172 | return Map(propertyInfo); 173 | } 174 | 175 | /// 176 | /// 设置实体属性映射,支持链式调用 177 | /// 178 | /// 实体属性元数据访问器 179 | /// 实体属性映射器 180 | protected PropertyMap Map(PropertyInfo propertyInfo) 181 | { 182 | PropertyMap result = new PropertyMap(propertyInfo); 183 | this.GuardForDuplicatePropertyMap(result); 184 | Properties.Add(result); 185 | return result; 186 | } 187 | 188 | private void GuardForDuplicatePropertyMap(PropertyMap result) 189 | { 190 | if (Properties.Any(p => p.Name.Equals(result.Name))) 191 | { 192 | throw new ArgumentException(string.Format("Duplicate mapping for property {0} detected.",result.Name)); 193 | } 194 | } 195 | } 196 | } -------------------------------------------------------------------------------- /src/DapperDal/Mapper/PluralizedAutoClassMapper.cs: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/arbing/DapperDal/bdb0beb99f3479e385bbad9970bbc4dda18ab925/src/DapperDal/Mapper/PluralizedAutoClassMapper.cs -------------------------------------------------------------------------------- /src/DapperDal/Mapper/PropertyMap.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Reflection; 3 | 4 | namespace DapperDal.Mapper 5 | { 6 | /// 7 | /// 实体属性映射器接口 8 | /// 9 | public interface IPropertyMap 10 | { 11 | /// 12 | /// 属性名 13 | /// 14 | string Name { get; } 15 | 16 | /// 17 | /// 属性对应表字段名 18 | /// 19 | string ColumnName { get; } 20 | 21 | /// 22 | /// 属性是否忽略 23 | /// 24 | bool Ignored { get; } 25 | 26 | /// 27 | /// 属性是否只读 28 | /// 29 | bool IsReadOnly { get; } 30 | 31 | /// 32 | /// 属性类型 33 | /// 34 | KeyType KeyType { get; } 35 | 36 | /// 37 | /// 属性元数据访问器 38 | /// 39 | PropertyInfo PropertyInfo { get; } 40 | } 41 | 42 | /// 43 | /// 实体属性映射器类 44 | /// 45 | public class PropertyMap : IPropertyMap 46 | { 47 | /// 48 | /// 初始化实体属性映射器 49 | /// 50 | /// 属性元数据访问器 51 | public PropertyMap(PropertyInfo propertyInfo) 52 | { 53 | PropertyInfo = propertyInfo; 54 | ColumnName = PropertyInfo.Name; 55 | } 56 | 57 | /// 58 | public string Name 59 | { 60 | get { return PropertyInfo.Name; } 61 | } 62 | 63 | /// 64 | public string ColumnName { get; private set; } 65 | 66 | /// 67 | public KeyType KeyType { get; private set; } 68 | 69 | /// 70 | public bool Ignored { get; private set; } 71 | 72 | /// 73 | public bool IsReadOnly { get; private set; } 74 | 75 | /// 76 | public PropertyInfo PropertyInfo { get; private set; } 77 | 78 | /// 79 | /// 设置实体属性和表字段的映射,支持链式调用 80 | /// 81 | /// 表字段名 82 | /// 实体属性映射器 83 | public PropertyMap Column(string columnName) 84 | { 85 | ColumnName = columnName; 86 | return this; 87 | } 88 | 89 | /// 90 | /// 设置实体属性类型,支持链式调用 91 | /// 92 | /// 属性类型 93 | /// 实体属性映射器 94 | public PropertyMap Key(KeyType keyType) 95 | { 96 | if (Ignored) 97 | { 98 | throw new ArgumentException(string.Format("'{0}' is ignored and cannot be made a key field. ", Name)); 99 | } 100 | 101 | if (IsReadOnly) 102 | { 103 | throw new ArgumentException(string.Format("'{0}' is readonly and cannot be made a key field. ", Name)); 104 | } 105 | 106 | KeyType = keyType; 107 | return this; 108 | } 109 | 110 | /// 111 | /// 设置实体属性忽略,支持链式调用 112 | /// 113 | /// 实体属性映射器 114 | public PropertyMap Ignore() 115 | { 116 | if (KeyType != KeyType.NotAKey) 117 | { 118 | throw new ArgumentException(string.Format("'{0}' is a key field and cannot be ignored.", Name)); 119 | } 120 | 121 | Ignored = true; 122 | return this; 123 | } 124 | 125 | /// 126 | /// 设置实体属性只读,支持链式调用 127 | /// 128 | /// 实体属性映射器 129 | public PropertyMap ReadOnly() 130 | { 131 | if (KeyType != KeyType.NotAKey) 132 | { 133 | throw new ArgumentException(string.Format("'{0}' is a key field and cannot be marked readonly.", Name)); 134 | } 135 | 136 | IsReadOnly = true; 137 | return this; 138 | } 139 | } 140 | 141 | /// 142 | /// 属性类型枚举 143 | /// 144 | public enum KeyType 145 | { 146 | /// 147 | /// 属性不是键,且不自增的 148 | /// The property is not a key and is not automatically managed. 149 | /// 150 | NotAKey, 151 | 152 | /// 153 | /// 属性是自增主键 154 | /// The property is an integery-based identity generated from the database. 155 | /// 156 | Identity, 157 | 158 | /// 159 | /// 属性是触发主键 160 | /// The property is an identity generated by the database trigger. 161 | /// 162 | TriggerIdentity, 163 | 164 | /// 165 | /// 属性是GUID 166 | /// The property is a Guid identity which is automatically managed. 167 | /// 168 | Guid, 169 | 170 | /// 171 | /// 属性是不自增的键 172 | /// The property is a key that is not automatically managed. 173 | /// 174 | Assigned 175 | } 176 | } -------------------------------------------------------------------------------- /src/DapperDal/Predicate/GetMultiplePredicate.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | 4 | namespace DapperDal.Predicate 5 | { 6 | /// 7 | /// 表示多结果集的谓词组 8 | /// 9 | public class GetMultiplePredicate 10 | { 11 | private readonly List _items; 12 | 13 | /// 14 | /// 初始化多结果集的谓词组 15 | /// 16 | public GetMultiplePredicate() 17 | { 18 | _items = new List(); 19 | } 20 | 21 | /// 22 | /// 谓词组集合 23 | /// 24 | public IEnumerable Items 25 | { 26 | get { return _items.AsReadOnly(); } 27 | } 28 | 29 | /// 30 | /// 添加一条结果集谓词组 31 | /// 32 | /// 谓词 33 | /// 排序条件 34 | /// 结果集实体类型 35 | public void Add(IPredicate predicate, IList sort = null) where T : class 36 | { 37 | _items.Add(new GetMultiplePredicateItem 38 | { 39 | Value = predicate, 40 | Type = typeof(T), 41 | Sort = sort 42 | }); 43 | } 44 | 45 | /// 46 | /// 添加一条结果集谓词组 47 | /// 48 | /// 谓词 49 | /// 结果集实体类型 50 | public void Add(object id) where T : class 51 | { 52 | _items.Add(new GetMultiplePredicateItem 53 | { 54 | Value = id, 55 | Type = typeof (T) 56 | }); 57 | } 58 | 59 | /// 60 | /// 表示多结果集的谓词组的项目 61 | /// 62 | public class GetMultiplePredicateItem 63 | { 64 | /// 65 | /// 谓词组值对象 66 | /// 67 | public object Value { get; set; } 68 | 69 | /// 70 | /// 结果集实体类型 71 | /// 72 | public Type Type { get; set; } 73 | 74 | /// 75 | /// 排序条件列表 76 | /// 77 | public IList Sort { get; set; } 78 | } 79 | } 80 | } -------------------------------------------------------------------------------- /src/DapperDal/Predicate/GetMultipleResult.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using Dapper; 3 | 4 | namespace DapperDal.Predicate 5 | { 6 | /// 7 | /// 多结果集读取器接口 8 | /// 9 | public interface IMultipleResultReader 10 | { 11 | /// 12 | /// 获取结果集 13 | /// 14 | /// 结果集实体类型 15 | /// 实体集合 16 | IEnumerable Read(); 17 | } 18 | 19 | /// 20 | /// 多结果集批量读取类 21 | /// 22 | public class GridReaderResultReader : IMultipleResultReader 23 | { 24 | private readonly SqlMapper.GridReader _reader; 25 | 26 | /// 27 | /// 初始化多结果集批量读取类 28 | /// 29 | /// 30 | public GridReaderResultReader(SqlMapper.GridReader reader) 31 | { 32 | _reader = reader; 33 | } 34 | 35 | /// 36 | public IEnumerable Read() 37 | { 38 | return _reader.Read(); 39 | } 40 | } 41 | 42 | /// 43 | /// 多结果集顺次读取类 44 | /// 45 | public class SequenceReaderResultReader : IMultipleResultReader 46 | { 47 | private readonly Queue _items; 48 | 49 | /// 50 | /// 初始化多结果集顺次读取类 51 | /// 52 | /// 53 | public SequenceReaderResultReader(IEnumerable items) 54 | { 55 | _items = new Queue(items); 56 | } 57 | 58 | /// 59 | public IEnumerable Read() 60 | { 61 | SqlMapper.GridReader reader = _items.Dequeue(); 62 | return reader.Read(); 63 | } 64 | } 65 | } -------------------------------------------------------------------------------- /src/DapperDal/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Reflection; 3 | using System.Runtime.CompilerServices; 4 | using System.Runtime.InteropServices; 5 | 6 | // 有关程序集的一般信息由以下 7 | // 控制。更改这些特性值可修改 8 | // 与程序集关联的信息。 9 | [assembly: AssemblyTitle("DapperDal")] 10 | [assembly: AssemblyDescription("")] 11 | [assembly: AssemblyConfiguration("")] 12 | [assembly: AssemblyCompany("")] 13 | [assembly: AssemblyProduct("DapperDal")] 14 | [assembly: AssemblyCopyright("Copyright © 2017")] 15 | [assembly: AssemblyTrademark("")] 16 | [assembly: AssemblyCulture("")] 17 | 18 | // 将 ComVisible 设置为 false 会使此程序集中的类型 19 | //对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型 20 | //请将此类型的 ComVisible 特性设置为 true。 21 | [assembly: ComVisible(false)] 22 | 23 | // 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID 24 | [assembly: Guid("64cca848-7660-43ee-abae-91effe765e41")] 25 | 26 | [assembly: InternalsVisibleTo("DapperDal.Test")] 27 | 28 | // 程序集的版本信息由下列四个值组成: 29 | // 30 | // 主版本 31 | // 次版本 32 | // 生成号 33 | // 修订号 34 | // 35 | // 可以指定所有值,也可以使用以下所示的 "*" 预置版本号和修订号 36 | //通过使用 "*",如下所示: 37 | // [assembly: AssemblyVersion("1.0.*")] 38 | [assembly: AssemblyVersion("1.5.19.0")] 39 | [assembly: AssemblyFileVersion("1.5.19.0")] 40 | [assembly: AssemblyInformationalVersion("1.5.19")] 41 | 42 | [assembly: CLSCompliant(true)] 43 | -------------------------------------------------------------------------------- /src/DapperDal/Sql/SqlServerDialect.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | 6 | namespace DapperDal.Sql 7 | { 8 | /// 9 | /// SQL Server方言类 10 | /// 11 | public class SqlServerDialect : SqlDialectBase 12 | { 13 | /// 14 | public override char OpenQuote 15 | { 16 | get { return '['; } 17 | } 18 | 19 | /// 20 | public override char CloseQuote 21 | { 22 | get { return ']'; } 23 | } 24 | 25 | /// 26 | public override string GetIdentitySql(string tableName) 27 | { 28 | return string.Format("SELECT CAST(SCOPE_IDENTITY() AS BIGINT) AS [Id]"); 29 | } 30 | 31 | /// 32 | public override string GetPagingSql(string sql, int page, int resultsPerPage, IDictionary parameters) 33 | { 34 | int startValue = (page * resultsPerPage) + 1; 35 | return GetSetSql(sql, startValue, resultsPerPage, parameters); 36 | } 37 | 38 | /// 39 | public override string GetSetSql(string sql, int firstResult, int maxResults, IDictionary parameters) 40 | { 41 | if (string.IsNullOrEmpty(sql)) 42 | { 43 | throw new ArgumentNullException("SQL"); 44 | } 45 | 46 | if (parameters == null) 47 | { 48 | throw new ArgumentNullException("Parameters"); 49 | } 50 | 51 | int selectIndex = GetSelectEnd(sql) + 1; 52 | string orderByClause = GetOrderByClause(sql); 53 | if (orderByClause == null) 54 | { 55 | orderByClause = "ORDER BY CURRENT_TIMESTAMP"; 56 | } 57 | 58 | 59 | string projectedColumns = GetColumnNames(sql).Aggregate(new StringBuilder(), (sb, s) => (sb.Length == 0 ? sb : sb.Append(", ")).Append(GetColumnName("_proj", s, null)), sb => sb.ToString()); 60 | string newSql = sql 61 | .Replace(" " + orderByClause, string.Empty) 62 | .Insert(selectIndex, string.Format("ROW_NUMBER() OVER(ORDER BY {0}) AS {1}, ", orderByClause.Substring(9), GetColumnName(null, "_row_number", null))); 63 | 64 | string result = string.Format("SELECT TOP({0}) {1} FROM ({2}) [_proj] WHERE {3} >= @_pageStartRow ORDER BY {3}", 65 | maxResults, projectedColumns.Trim(), newSql, GetColumnName("_proj", "_row_number", null)); 66 | 67 | parameters.Add("@_pageStartRow", firstResult); 68 | return result; 69 | } 70 | 71 | /// 72 | /// 获取SQL语句的排序部分语句 73 | /// 74 | /// SQL语句 75 | /// 排序部分语句 76 | protected string GetOrderByClause(string sql) 77 | { 78 | int orderByIndex = sql.LastIndexOf(" ORDER BY ", StringComparison.InvariantCultureIgnoreCase); 79 | if (orderByIndex == -1) 80 | { 81 | return null; 82 | } 83 | 84 | string result = sql.Substring(orderByIndex).Trim(); 85 | 86 | int whereIndex = result.IndexOf(" WHERE ", StringComparison.InvariantCultureIgnoreCase); 87 | if (whereIndex == -1) 88 | { 89 | return result; 90 | } 91 | 92 | return result.Substring(0, whereIndex).Trim(); 93 | } 94 | 95 | /// 96 | /// 获取SQL语句的FROM索引 97 | /// 98 | /// SQL语句 99 | /// FROM索引 100 | protected int GetFromStart(string sql) 101 | { 102 | int selectCount = 0; 103 | string[] words = sql.Split(' '); 104 | int fromIndex = 0; 105 | foreach (var word in words) 106 | { 107 | if (word.Equals("SELECT", StringComparison.InvariantCultureIgnoreCase)) 108 | { 109 | selectCount++; 110 | } 111 | 112 | if (word.Equals("FROM", StringComparison.InvariantCultureIgnoreCase)) 113 | { 114 | selectCount--; 115 | if (selectCount == 0) 116 | { 117 | break; 118 | } 119 | } 120 | 121 | fromIndex += word.Length + 1; 122 | } 123 | 124 | return fromIndex; 125 | } 126 | 127 | /// 128 | /// 获取SQL语句的SELECT索引 129 | /// 130 | /// SQL语句 131 | /// SELECT索引 132 | protected virtual int GetSelectEnd(string sql) 133 | { 134 | if (sql.StartsWith("SELECT DISTINCT", StringComparison.InvariantCultureIgnoreCase)) 135 | { 136 | return 15; 137 | } 138 | 139 | if (sql.StartsWith("SELECT", StringComparison.InvariantCultureIgnoreCase)) 140 | { 141 | return 6; 142 | } 143 | 144 | throw new ArgumentException("SQL must be a SELECT statement.", "sql"); 145 | } 146 | 147 | /// 148 | /// 获取SQL语句里的所有字段名 149 | /// 150 | /// SQL语句 151 | /// 字段名列表 152 | protected virtual IList GetColumnNames(string sql) 153 | { 154 | int start = GetSelectEnd(sql); 155 | int stop = GetFromStart(sql); 156 | string[] columnSql = sql.Substring(start, stop - start).Split(','); 157 | List result = new List(); 158 | foreach (string c in columnSql) 159 | { 160 | int index = c.IndexOf(" AS ", StringComparison.InvariantCultureIgnoreCase); 161 | if (index > 0) 162 | { 163 | result.Add(c.Substring(index + 4).Trim()); 164 | continue; 165 | } 166 | 167 | string[] colParts = c.Split('.'); 168 | result.Add(colParts[colParts.Length - 1].Trim()); 169 | } 170 | 171 | return result; 172 | } 173 | 174 | /// 175 | public override string SelectLimit(string sql, int limit) 176 | { 177 | const string searchFor = "SELECT "; 178 | if (sql.Contains("TOP (")) 179 | { 180 | return sql; 181 | } 182 | 183 | return sql.Insert(sql.IndexOf(searchFor, StringComparison.OrdinalIgnoreCase) + searchFor.Length, 184 | string.Format("TOP ({0}) ", limit)); 185 | } 186 | 187 | /// 188 | public override string SetNolock(string sql) 189 | { 190 | const string withNolock = " WITH (NOLOCK)"; 191 | const string where = " WHERE "; 192 | const string orderby = " ORDER BY "; 193 | 194 | if (sql.Contains(withNolock)) 195 | { 196 | return sql; 197 | } 198 | 199 | if (sql.Contains(where)) 200 | { 201 | return sql.Insert(sql.IndexOf(where, StringComparison.OrdinalIgnoreCase), withNolock); 202 | } 203 | 204 | if (sql.Contains(orderby)) 205 | { 206 | return sql.Insert(sql.IndexOf(orderby, StringComparison.OrdinalIgnoreCase), withNolock); 207 | } 208 | 209 | return string.Concat(sql, withNolock); 210 | } 211 | } 212 | } -------------------------------------------------------------------------------- /src/DapperDal/Utils/ExpressionExtensions.cs: -------------------------------------------------------------------------------- 1 | // https://github.com/alexfoxgill/ExpressionTools 2 | 3 | using System; 4 | using System.Collections.Generic; 5 | using System.Linq.Expressions; 6 | using DapperDal.Expressions; 7 | 8 | namespace DapperDal.Utils 9 | { 10 | /// 11 | /// 表达式转换扩展 12 | /// 13 | internal static class ExpressionExtensions 14 | { 15 | /// 16 | /// Combines two expressions (a -> b) and (a -> c) with a combining expression ((b,c) -> d) to form an expression (a -> d) 17 | /// 18 | /// The input type of both primary expressions 19 | /// The result type of the first primary expression 20 | /// The result type of the second primary expression 21 | /// The result type of the combining expression 22 | /// The first primary expression 23 | /// The second primary expression 24 | /// The combining expression 25 | /// A composite of all three expressions, with the first two substituted in place of the third's parameters 26 | public static Expression> Combine( 27 | this Expression> first, 28 | Expression> second, 29 | Expression> combineExpr) 30 | { 31 | // replace second's parameter with first's 32 | var inputParameter = first.Parameters[0]; 33 | var expr2Body = second.Body.Replace(second.Parameters[0], inputParameter); 34 | 35 | // then replace both expressions in combining func 36 | var map = new Dictionary 37 | { 38 | { combineExpr.Parameters[0], first.Body }, 39 | { combineExpr.Parameters[1], expr2Body } 40 | }; 41 | var replaced = combineExpr.Body.Replace(map); 42 | return Expression.Lambda>(replaced, inputParameter); 43 | } 44 | 45 | /// 46 | /// Composes two expressions (a -> b) and (b -> c) to form an expression (a -> c) 47 | /// 48 | /// The input to the first expression 49 | /// The output of the first expression and input to the second 50 | /// The output of the second expression 51 | /// The first expression 52 | /// The second expression 53 | /// A composite of the two expressions, with the first substituted in place of the second's parameter 54 | public static Expression> Compose( 55 | this Expression> first, 56 | Expression> second) 57 | { 58 | var replaced = second.Body.Replace(second.Parameters[0], first.Body); 59 | return Expression.Lambda>(replaced, first.Parameters[0]); 60 | } 61 | 62 | /// 63 | /// Applies null coalescence to an expression resulting in a nullable type 64 | /// 65 | /// The input to the expression 66 | /// The nullable result 67 | /// The expression 68 | /// The default value with which to replace a null value. Defaults to default(TResult) 69 | /// An expression in which a null result is replaced with the given value 70 | public static Expression> Coalesce(this Expression> expr, TResult defaultValue = default(TResult)) 71 | where TResult : struct 72 | { 73 | return expr.Compose(x => x ?? defaultValue); 74 | } 75 | } 76 | } 77 | -------------------------------------------------------------------------------- /src/DapperDal/Utils/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 DapperDal.Utils 9 | { 10 | /// 11 | /// 反射工具方法 12 | /// 13 | internal static class ReflectionHelper 14 | { 15 | private static List _simpleTypes = new List 16 | { 17 | typeof(byte), 18 | typeof(sbyte), 19 | typeof(short), 20 | typeof(ushort), 21 | typeof(int), 22 | typeof(uint), 23 | typeof(long), 24 | typeof(ulong), 25 | typeof(float), 26 | typeof(double), 27 | typeof(decimal), 28 | typeof(bool), 29 | typeof(string), 30 | typeof(char), 31 | typeof(Guid), 32 | typeof(DateTime), 33 | typeof(DateTimeOffset), 34 | typeof(byte[]) 35 | }; 36 | 37 | /// 38 | /// 从表达式获取成员元数据访问器对象 39 | /// 40 | /// 表达式 41 | /// 成员元数据访问器对象 42 | public static MemberInfo GetProperty(LambdaExpression lambda) 43 | { 44 | Expression expr = lambda; 45 | for (; ; ) 46 | { 47 | switch (expr.NodeType) 48 | { 49 | case ExpressionType.Lambda: 50 | expr = ((LambdaExpression)expr).Body; 51 | break; 52 | case ExpressionType.Convert: 53 | expr = ((UnaryExpression)expr).Operand; 54 | break; 55 | case ExpressionType.MemberAccess: 56 | MemberExpression memberExpression = (MemberExpression)expr; 57 | MemberInfo mi = memberExpression.Member; 58 | return mi; 59 | default: 60 | return null; 61 | } 62 | } 63 | } 64 | 65 | /// 66 | /// 对象生成属性名及属性值的字典返回 67 | /// 68 | /// 对象 69 | /// 属性名及属性值的字典 70 | public static IDictionary GetObjectValues(object obj) 71 | { 72 | IDictionary result = new Dictionary(); 73 | if (obj == null) 74 | { 75 | return result; 76 | } 77 | 78 | 79 | foreach (var propertyInfo in obj.GetType().GetProperties()) 80 | { 81 | string name = propertyInfo.Name; 82 | object value = propertyInfo.GetValue(obj, null); 83 | result[name] = value; 84 | } 85 | 86 | return result; 87 | } 88 | 89 | /// 90 | /// 拼接查询字段名 91 | /// 92 | /// 查询字段名列表 93 | /// 拼接分割字符 94 | /// 拼接后的语句 95 | public static string AppendStrings(this IEnumerable list, string seperator = ", ") 96 | { 97 | return list.Aggregate( 98 | new StringBuilder(), 99 | (sb, s) => (sb.Length == 0 ? sb : sb.Append(seperator)).Append(s), 100 | sb => sb.ToString()); 101 | } 102 | 103 | /// 104 | /// 类型是否是简单类型 105 | /// 106 | /// 类型 107 | /// 是否是简单类型 108 | public static bool IsSimpleType(Type type) 109 | { 110 | Type actualType = type; 111 | if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>)) 112 | { 113 | actualType = type.GetGenericArguments()[0]; 114 | } 115 | 116 | return _simpleTypes.Contains(actualType); 117 | } 118 | 119 | /// 120 | /// 生成SQL参数片段 121 | /// 122 | /// 参数列表 123 | /// 参数名 124 | /// 参数前缀 125 | /// 参数片段 126 | public static string GetParameterName(this IDictionary parameters, string parameterName, char parameterPrefix) 127 | { 128 | return string.Format("{0}{1}_{2}", parameterPrefix, parameterName, parameters.Count); 129 | } 130 | 131 | /// 132 | /// 生成SQL参数片段 133 | /// 134 | /// 参数列表 135 | /// 参数名 136 | /// 参数值 137 | /// 参数前缀 138 | /// 参数片段 139 | public static string SetParameterName(this IDictionary parameters, string parameterName, object value, char parameterPrefix) 140 | { 141 | string name = parameters.GetParameterName(parameterName, parameterPrefix); 142 | parameters.Add(name, value); 143 | return name; 144 | } 145 | } 146 | } -------------------------------------------------------------------------------- /src/DapperDal/packages.config: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | -------------------------------------------------------------------------------- /test/DapperDal.Test.Entities/DapperDal.Test.Entities.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | Debug 5 | AnyCPU 6 | {1EF2B04A-7E97-4C53-8AFB-D90E815CFB05} 7 | Library 8 | Properties 9 | DapperDal.Test.Entities 10 | DapperDal.Test.Entities 11 | v4.0 12 | 512 13 | 14 | 15 | true 16 | full 17 | false 18 | bin\Debug\ 19 | DEBUG;TRACE 20 | prompt 21 | 4 22 | 23 | 24 | pdbonly 25 | true 26 | bin\Release\ 27 | TRACE 28 | prompt 29 | 4 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | -------------------------------------------------------------------------------- /test/DapperDal.Test.Entities/ExternallyMapped.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace DapperDal.Test.Entities 4 | { 5 | public class ExternallyMapped 6 | { 7 | public int Id { get; set; } 8 | public string Name { get; set; } 9 | public DateTime DateCreated { get; set; } 10 | public bool Active { get; set; } 11 | } 12 | } -------------------------------------------------------------------------------- /test/DapperDal.Test.Entities/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.CompilerServices; 3 | using System.Runtime.InteropServices; 4 | 5 | // 有关程序集的一般信息由以下 6 | // 控制。更改这些特性值可修改 7 | // 与程序集关联的信息。 8 | [assembly: AssemblyTitle("DapperDal.Test.Entities")] 9 | [assembly: AssemblyDescription("")] 10 | [assembly: AssemblyConfiguration("")] 11 | [assembly: AssemblyCompany("")] 12 | [assembly: AssemblyProduct("DapperDal.Test.Entities")] 13 | [assembly: AssemblyCopyright("Copyright © 2017")] 14 | [assembly: AssemblyTrademark("")] 15 | [assembly: AssemblyCulture("")] 16 | 17 | // 将 ComVisible 设置为 false 会使此程序集中的类型 18 | //对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型 19 | //请将此类型的 ComVisible 特性设置为 true。 20 | [assembly: ComVisible(false)] 21 | 22 | // 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID 23 | [assembly: Guid("1ef2b04a-7e97-4c53-8afb-d90e815cfb05")] 24 | 25 | // 程序集的版本信息由下列四个值组成: 26 | // 27 | // 主版本 28 | // 次版本 29 | // 生成号 30 | // 修订号 31 | // 32 | // 可以指定所有值,也可以使用以下所示的 "*" 预置版本号和修订号 33 | //通过使用 "*",如下所示: 34 | // [assembly: AssemblyVersion("1.0.*")] 35 | [assembly: AssemblyVersion("1.0.0.0")] 36 | [assembly: AssemblyFileVersion("1.0.0.0")] 37 | -------------------------------------------------------------------------------- /test/DapperDal.Test.Maps/DapperDal.Test.Maps.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | Debug 5 | AnyCPU 6 | {E335BE03-0A91-4A41-8631-71044CC46310} 7 | Library 8 | Properties 9 | DapperDal.Test.Maps 10 | DapperDal.Test.Maps 11 | v4.0 12 | 512 13 | 14 | 15 | true 16 | full 17 | false 18 | bin\Debug\ 19 | DEBUG;TRACE 20 | prompt 21 | 4 22 | 23 | 24 | pdbonly 25 | true 26 | bin\Release\ 27 | TRACE 28 | prompt 29 | 4 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | {1ef2b04a-7e97-4c53-8afb-d90e815cfb05} 47 | DapperDal.Test.Entities 48 | 49 | 50 | {64cca848-7660-43ee-abae-91effe765e41} 51 | DapperDal 52 | 53 | 54 | 55 | -------------------------------------------------------------------------------- /test/DapperDal.Test.Maps/ExternallyMappedMap.cs: -------------------------------------------------------------------------------- 1 | using DapperDal.Mapper; 2 | using DapperDal.Test.Entities; 3 | 4 | namespace DapperDal.Test.Maps 5 | { 6 | public class ExternallyMappedMap 7 | { 8 | public class ExternallyMappedMapper : ClassMapper 9 | { 10 | public ExternallyMappedMapper() 11 | { 12 | Table("External"); 13 | Map(x => x.Id).Column("ExternalId"); 14 | AutoMap(); 15 | } 16 | } 17 | } 18 | } -------------------------------------------------------------------------------- /test/DapperDal.Test.Maps/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.CompilerServices; 3 | using System.Runtime.InteropServices; 4 | 5 | // 有关程序集的一般信息由以下 6 | // 控制。更改这些特性值可修改 7 | // 与程序集关联的信息。 8 | [assembly: AssemblyTitle("DapperDal.Test.Maps")] 9 | [assembly: AssemblyDescription("")] 10 | [assembly: AssemblyConfiguration("")] 11 | [assembly: AssemblyCompany("")] 12 | [assembly: AssemblyProduct("DapperDal.Test.Maps")] 13 | [assembly: AssemblyCopyright("Copyright © 2017")] 14 | [assembly: AssemblyTrademark("")] 15 | [assembly: AssemblyCulture("")] 16 | 17 | // 将 ComVisible 设置为 false 会使此程序集中的类型 18 | //对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型 19 | //请将此类型的 ComVisible 特性设置为 true。 20 | [assembly: ComVisible(false)] 21 | 22 | // 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID 23 | [assembly: Guid("e335be03-0a91-4a41-8631-71044cc46310")] 24 | 25 | // 程序集的版本信息由下列四个值组成: 26 | // 27 | // 主版本 28 | // 次版本 29 | // 生成号 30 | // 修订号 31 | // 32 | // 可以指定所有值,也可以使用以下所示的 "*" 预置版本号和修订号 33 | //通过使用 "*",如下所示: 34 | // [assembly: AssemblyVersion("1.0.*")] 35 | [assembly: AssemblyVersion("1.0.0.0")] 36 | [assembly: AssemblyFileVersion("1.0.0.0")] 37 | -------------------------------------------------------------------------------- /test/DapperDal.Test/App.config: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /test/DapperDal.Test/Dal/CarDal.cs: -------------------------------------------------------------------------------- 1 | using DapperDal.Test.Entities; 2 | 3 | namespace DapperDal.Test.Dal 4 | { 5 | public class CarDal : DalBase 6 | { 7 | public CarDal() : base(ConnectionNames.Default) 8 | { 9 | } 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /test/DapperDal.Test/Dal/ConnectionNames.cs: -------------------------------------------------------------------------------- 1 | namespace DapperDal.Test.Dal 2 | { 3 | public class ConnectionNames 4 | { 5 | public static string Default 6 | { 7 | get { return "Default"; } 8 | } 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /test/DapperDal.Test/Dal/PersonDal.cs: -------------------------------------------------------------------------------- 1 | using DapperDal.Test.Entities; 2 | 3 | namespace DapperDal.Test.Dal 4 | { 5 | public class PersonDal : DalBase 6 | { 7 | public PersonDal() : base(ConnectionNames.Default) 8 | { 9 | } 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /test/DapperDal.Test/DapperDal.Test.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | Debug 5 | AnyCPU 6 | {8BF8684B-E2F2-43A3-B5C7-B9C49F1810C5} 7 | Library 8 | Properties 9 | DapperDal.Test 10 | DapperDal.Test 11 | v4.0 12 | 512 13 | true 14 | publish\ 15 | true 16 | Disk 17 | false 18 | Foreground 19 | 7 20 | Days 21 | false 22 | false 23 | true 24 | 0 25 | 1.0.0.%2a 26 | false 27 | false 28 | true 29 | 30 | 31 | true 32 | full 33 | false 34 | bin\Debug\ 35 | DEBUG;TRACE 36 | prompt 37 | 4 38 | 39 | 40 | pdbonly 41 | true 42 | bin\Release\ 43 | TRACE 44 | prompt 45 | 4 46 | 47 | 48 | 49 | ..\..\packages\Dapper.1.50.2\lib\net40\Dapper.dll 50 | 51 | 52 | ..\..\packages\Moq.4.0.10827\lib\NET40\Moq.dll 53 | 54 | 55 | ..\..\packages\NUnit.3.6.1\lib\net40\nunit.framework.dll 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | {1ef2b04a-7e97-4c53-8afb-d90e815cfb05} 93 | DapperDal.Test.Entities 94 | 95 | 96 | {e335be03-0a91-4a41-8631-71044cc46310} 97 | DapperDal.Test.Maps 98 | 99 | 100 | {64cca848-7660-43ee-abae-91effe765e41} 101 | DapperDal 102 | 103 | 104 | 105 | 106 | 107 | Designer 108 | 109 | 110 | 111 | 112 | 113 | 114 | 115 | 116 | 117 | 118 | 119 | 120 | 121 | False 122 | .NET Framework 3.5 SP1 123 | false 124 | 125 | 126 | 127 | 128 | 129 | 130 | 131 | 132 | 133 | 134 | 135 | 136 | 137 | 138 | 145 | -------------------------------------------------------------------------------- /test/DapperDal.Test/Entities/CarEntity.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace DapperDal.Test.Entities 4 | { 5 | public class CarEntity 6 | { 7 | public int CarId { get; set; } 8 | 9 | public string CarName { get; set; } 10 | 11 | public int BrandId { get; set; } 12 | 13 | public DateTime CreateTime { get; set; } 14 | 15 | public DateTime UpdateTime { get; set; } 16 | 17 | public bool IsActive { get; set; } 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /test/DapperDal.Test/Entities/PersonEntity.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | 4 | namespace DapperDal.Test.Entities 5 | { 6 | public class PersonEntity 7 | { 8 | public long PersonId { get; set; } 9 | 10 | public string PersonName { get; set; } 11 | 12 | public int CarId { get; set; } 13 | 14 | public DateTime CreateTime { get; set; } 15 | 16 | public DateTime UpdateTime { get; set; } 17 | 18 | public short IsActive { get; set; } 19 | } 20 | 21 | } -------------------------------------------------------------------------------- /test/DapperDal.Test/Helpers/DatabaseInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Data; 2 | using DapperDal.Sql; 3 | 4 | namespace DapperDal.Test.Helpers 5 | { 6 | public class DatabaseInfo 7 | { 8 | public IDbConnection Connection { get; set; } 9 | public ISqlDialect Dialect { get; set; } 10 | } 11 | } -------------------------------------------------------------------------------- /test/DapperDal.Test/Helpers/Protected.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Linq; 3 | using System.Linq.Expressions; 4 | using System.Reflection; 5 | 6 | namespace DapperDal.Test.Helpers 7 | { 8 | public class Protected 9 | { 10 | private readonly object _obj; 11 | 12 | public Protected(object obj) 13 | { 14 | if (obj == null) 15 | { 16 | throw new ArgumentException("object cannot be null.", "obj"); 17 | } 18 | 19 | _obj = obj; 20 | } 21 | 22 | public static Expression IsNull() 23 | { 24 | Expression> expr = () => typeof(T); 25 | return expr.Body; 26 | } 27 | 28 | public void RunMethod(string name, params object[] parameters) 29 | { 30 | InvokeMethod(name, null, parameters); 31 | } 32 | 33 | public T RunMethod(string name, params object[] parameters) 34 | { 35 | return (T)InvokeMethod(name, null, parameters); 36 | } 37 | 38 | public void RunGenericMethod(string name, Type[] genericTypes, params object[] parameters) 39 | { 40 | InvokeMethod(name, genericTypes, parameters); 41 | } 42 | 43 | public TResult RunGenericMethod(string name, Type[] genericTypes, params object[] parameters) 44 | { 45 | return (TResult)InvokeMethod(name, genericTypes, parameters); 46 | } 47 | 48 | public object InvokeMethod(string name, Type[] genericTypes, object[] parameters) 49 | { 50 | object[] pa = parameters.Select(p => 51 | { 52 | if (p is ConstantExpression) 53 | { 54 | return null; 55 | } 56 | 57 | return p; 58 | }).ToArray(); 59 | MethodInfo method = GetMethod(name, parameters); 60 | try 61 | { 62 | if (genericTypes != null && genericTypes.Any()) 63 | { 64 | method = method.MakeGenericMethod(genericTypes); 65 | } 66 | 67 | return method.Invoke(_obj, pa); 68 | } 69 | catch (TargetInvocationException ex) 70 | { 71 | throw ex.InnerException; 72 | } 73 | } 74 | 75 | public MethodInfo GetMethod(string name, object[] parameters) 76 | { 77 | Type[] types = parameters.Select(p => 78 | { 79 | if (p is ConstantExpression) 80 | { 81 | return (Type)((ConstantExpression)p).Value; 82 | } 83 | 84 | return p.GetType(); 85 | }).ToArray(); 86 | MethodInfo method = _obj.GetType().GetMethod(name, BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public, null, types, null); 87 | if (method == null) 88 | { 89 | throw new ArgumentException(string.Format("{0} was not found in {1}.", name, _obj.GetType()), name); 90 | } 91 | 92 | return method; 93 | } 94 | } 95 | } -------------------------------------------------------------------------------- /test/DapperDal.Test/Helpers/TestHelpers.cs: -------------------------------------------------------------------------------- 1 | namespace DapperDal.Test.Helpers 2 | { 3 | public static class TestHelpers 4 | { 5 | public static Protected TestProtected(this object obj) 6 | { 7 | return new Protected(obj); 8 | } 9 | } 10 | } -------------------------------------------------------------------------------- /test/DapperDal.Test/IntegrationTests/NonCrudFixture.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq.Expressions; 4 | using System.Reflection; 5 | using DapperDal.Mapper; 6 | using DapperDal.Test.Entities; 7 | using DapperDal.Test.Maps; 8 | using NUnit.Framework; 9 | 10 | namespace DapperDal.Test.IntegrationTests 11 | { 12 | [TestFixture] 13 | public class NonCrudFixture 14 | { 15 | [TestFixture] 16 | public class GetNextGuidMethod 17 | { 18 | [Test] 19 | public void GetMultiple_DoesNotDuplicate() 20 | { 21 | List list = new List(); 22 | for (int i = 0; i < 1000; i++) 23 | { 24 | Guid id = DalConfiguration.Default.GetNextGuid(); 25 | Assert.IsFalse(list.Contains(id)); 26 | list.Add(id); 27 | } 28 | } 29 | } 30 | 31 | [TestFixture] 32 | public class GetMapMethod 33 | { 34 | [Test] 35 | public void NoMappingClass_ReturnsDefaultMapper() 36 | { 37 | var mapper = DalConfiguration.Default.GetMap(); 38 | Assert.AreEqual(typeof(AutoClassMapper), mapper.GetType()); 39 | } 40 | 41 | [Test] 42 | public void ClassMapperDescendant_Returns_DefinedClass() 43 | { 44 | var mapper = DalConfiguration.Default.GetMap(); 45 | Assert.AreEqual(typeof(EntityWithMapperMapper), mapper.GetType()); 46 | } 47 | 48 | [Test] 49 | public void ClassMapperInterface_Returns_DefinedMapper() 50 | { 51 | var mapper = DalConfiguration.Default.GetMap(); 52 | Assert.AreEqual(typeof(EntityWithInterfaceMapperMapper), mapper.GetType()); 53 | } 54 | 55 | [Test] 56 | public void MappingClass_ReturnsFromDifferentAssembly() 57 | { 58 | DalConfiguration.Default.SetMappingAssemblies(new[] { typeof(ExternallyMappedMap).Assembly }); 59 | var mapper = DalConfiguration.Default.GetMap(); 60 | Assert.AreEqual(typeof(ExternallyMappedMap.ExternallyMappedMapper), mapper.GetType()); 61 | 62 | DalConfiguration.Default.SetMappingAssemblies(null); 63 | mapper = DalConfiguration.Default.GetMap(); 64 | Assert.AreEqual(typeof(AutoClassMapper), mapper.GetType()); 65 | } 66 | 67 | private class EntityWithoutMapper 68 | { 69 | public int Id { get; set; } 70 | public string Name { get; set; } 71 | } 72 | 73 | private class EntityWithMapper 74 | { 75 | public string Key { get; set; } 76 | public string Value { get; set; } 77 | } 78 | 79 | private class EntityWithMapperMapper : ClassMapper 80 | { 81 | public EntityWithMapperMapper() 82 | { 83 | Map(p => p.Key).Column("EntityKey").Key(KeyType.Assigned); 84 | AutoMap(); 85 | } 86 | } 87 | 88 | private class EntityWithInterfaceMapper 89 | { 90 | public string Key { get; set; } 91 | public string Value { get; set; } 92 | } 93 | 94 | private class EntityWithInterfaceMapperMapper : IClassMapper 95 | { 96 | public string SchemaName { get; private set; } 97 | public string TableName { get; private set; } 98 | public IList Properties { get; private set; } 99 | public Type EntityType { get; private set; } 100 | 101 | public PropertyMap Map(Expression> expression) 102 | { 103 | throw new NotImplementedException(); 104 | } 105 | 106 | public PropertyMap Map(PropertyInfo propertyInfo) 107 | { 108 | throw new NotImplementedException(); 109 | } 110 | } 111 | } 112 | } 113 | } -------------------------------------------------------------------------------- /test/DapperDal.Test/IntegrationTests/SqlServer/Sql/CreateCarTable.sql: -------------------------------------------------------------------------------- 1 | IF (OBJECT_ID('Car') IS NOT NULL) 2 | BEGIN 3 | DROP TABLE Car 4 | END 5 | 6 | CREATE TABLE Car ( 7 | CarId INT IDENTITY(1,1) PRIMARY KEY, 8 | CarName NVARCHAR(50) NULL, 9 | BrandId INT NULL, 10 | [CreateTime] [DATETIME] NULL DEFAULT (GETDATE()), 11 | [UpdateTime] [DATETIME] NULL, 12 | [IsActive] [BIT] NULL DEFAULT ((0)) 13 | ) -------------------------------------------------------------------------------- /test/DapperDal.Test/IntegrationTests/SqlServer/Sql/CreateDatabase.sql: -------------------------------------------------------------------------------- 1 | USE master; 2 | 3 | IF EXISTS ( SELECT * 4 | FROM sysdatabases 5 | WHERE name = 'DapperDalTest' 6 | ) 7 | DROP DATABASE DapperDalTest; 8 | 9 | EXEC(' 10 | CREATE DATABASE DapperDalTest 11 | ') -------------------------------------------------------------------------------- /test/DapperDal.Test/IntegrationTests/SqlServer/Sql/CreatePersonProcedure.sql: -------------------------------------------------------------------------------- 1 | IF EXISTS ( SELECT * 2 | FROM sys.objects 3 | WHERE object_id = OBJECT_ID(N'P_GetPersonsByCarId') 4 | AND type IN (N'P', N'PC') ) 5 | BEGIN 6 | DROP PROCEDURE dbo.P_GetPersonsByCarId 7 | END 8 | 9 | EXEC(' 10 | CREATE PROCEDURE dbo.P_GetPersonsByCarId (@CarId INT) 11 | AS 12 | BEGIN 13 | SELECT * 14 | FROM Person 15 | WHERE CarId = @CarId; 16 | END 17 | ') 18 | 19 | IF EXISTS ( SELECT * 20 | FROM sys.objects 21 | WHERE object_id = OBJECT_ID(N'P_GetPersonModelsByCarId') 22 | AND type IN (N'P', N'PC') ) 23 | BEGIN 24 | DROP PROCEDURE dbo.P_GetPersonModelsByCarId 25 | END 26 | 27 | EXEC(' 28 | CREATE PROCEDURE dbo.P_GetPersonModelsByCarId (@CarId INT) 29 | AS 30 | BEGIN 31 | SELECT PersonName AS [Name] 32 | ,CarId 33 | FROM Person 34 | WHERE CarId = @CarId; 35 | END; 36 | ') 37 | 38 | IF EXISTS ( SELECT * 39 | FROM sys.objects 40 | WHERE object_id = OBJECT_ID(N'P_GetPersonMultipleModelsByCarId') 41 | AND type IN (N'P', N'PC') ) 42 | BEGIN 43 | DROP PROCEDURE dbo.P_GetPersonMultipleModelsByCarId 44 | END 45 | 46 | EXEC(' 47 | CREATE PROCEDURE dbo.P_GetPersonMultipleModelsByCarId (@CarId INT) 48 | AS 49 | BEGIN 50 | SELECT * 51 | FROM Person 52 | WHERE CarId = @CarId; 53 | 54 | SELECT PersonName AS [Name] 55 | ,CarId 56 | FROM Person 57 | WHERE CarId = @CarId; 58 | END; 59 | ') 60 | 61 | IF EXISTS ( SELECT * 62 | FROM sys.objects 63 | WHERE object_id = OBJECT_ID(N'P_GetPersonModelsByCarId_OutputCount') 64 | AND type IN (N'P', N'PC') ) 65 | BEGIN 66 | DROP PROCEDURE dbo.P_GetPersonModelsByCarId_OutputCount 67 | END 68 | 69 | EXEC(' 70 | CREATE PROCEDURE dbo.P_GetPersonModelsByCarId_OutputCount (@CarId INT, @TotalCount INT Output) 71 | AS 72 | BEGIN 73 | SELECT @TotalCount = COUNT(1) 74 | FROM Person 75 | WHERE CarId = @CarId; 76 | 77 | SELECT PersonName AS [Name] 78 | ,CarId 79 | FROM Person 80 | WHERE CarId = @CarId; 81 | END; 82 | ') 83 | 84 | IF EXISTS ( SELECT * 85 | FROM sys.objects 86 | WHERE object_id = OBJECT_ID(N'P_SetPersonsByCarId') 87 | AND type IN (N'P', N'PC') ) 88 | BEGIN 89 | DROP PROCEDURE dbo.P_SetPersonsByCarId 90 | END 91 | 92 | EXEC(' 93 | CREATE PROCEDURE dbo.P_SetPersonsByCarId (@CarId INT) 94 | AS 95 | BEGIN 96 | update Person set IsActive = 1 where CarId = @CarId; 97 | END; 98 | ') 99 | 100 | 101 | IF EXISTS ( SELECT * 102 | FROM sys.objects 103 | WHERE object_id = OBJECT_ID(N'P_SetPersonsByCarId_OutputCount') 104 | AND type IN (N'P', N'PC') ) 105 | BEGIN 106 | DROP PROCEDURE dbo.P_SetPersonsByCarId_OutputCount 107 | END 108 | 109 | EXEC(' 110 | CREATE PROCEDURE dbo.P_SetPersonsByCarId_OutputCount (@CarId INT, @TotalCount INT Output) 111 | AS 112 | BEGIN 113 | SELECT @TotalCount = COUNT(1) 114 | FROM Person 115 | WHERE CarId = @CarId; 116 | 117 | update Person set IsActive = 1 where CarId = @CarId; 118 | END; 119 | ') 120 | -------------------------------------------------------------------------------- /test/DapperDal.Test/IntegrationTests/SqlServer/Sql/CreatePersonTable.sql: -------------------------------------------------------------------------------- 1 | IF (OBJECT_ID('Person') IS NOT NULL) 2 | BEGIN 3 | DROP TABLE Person 4 | END 5 | 6 | CREATE TABLE Person ( 7 | PersonId INT IDENTITY(1,1) PRIMARY KEY, 8 | PersonName NVARCHAR(50) NULL, 9 | CarId INT NULL, 10 | [CreateTime] [DATETIME] NULL DEFAULT (GETDATE()), 11 | [UpdateTime] [DATETIME] NULL, 12 | [IsActive] [SMALLINT] NULL DEFAULT ((0)) 13 | ) -------------------------------------------------------------------------------- /test/DapperDal.Test/IntegrationTests/SqlServer/Sql/DropDatabase.sql: -------------------------------------------------------------------------------- 1 | DROP DATABASE DapperDalTest; 2 | -------------------------------------------------------------------------------- /test/DapperDal.Test/IntegrationTests/SqlServer/Sql/TruncateTable.sql: -------------------------------------------------------------------------------- 1 | TRUNCATE TABLE Car; 2 | TRUNCATE TABLE Person; 3 | -------------------------------------------------------------------------------- /test/DapperDal.Test/IntegrationTests/SqlServer/SqlServerBaseFixture.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Configuration; 4 | using System.Data.SqlClient; 5 | using System.IO; 6 | using System.Reflection; 7 | using Dapper; 8 | using NUnit.Framework; 9 | 10 | namespace DapperDal.Test.IntegrationTests.SqlServer 11 | { 12 | [SetUpFixture] 13 | public class MySetUpClass 14 | { 15 | [OneTimeSetUp] 16 | public void RunBeforeAnyTests() 17 | { 18 | CreateDatabase(); 19 | 20 | var connectionString = ConfigurationManager.ConnectionStrings["Default"]; 21 | var connection = new SqlConnection(connectionString.ConnectionString); 22 | var files = new List 23 | { 24 | ReadScriptFile("CreateCarTable"), 25 | ReadScriptFile("CreatePersonTable"), 26 | ReadScriptFile("CreatePersonProcedure"), 27 | }; 28 | 29 | foreach (var setupFile in files) 30 | { 31 | connection.Execute(setupFile); 32 | } 33 | 34 | DalConfiguration.Default.OutputSql = Console.WriteLine; 35 | } 36 | 37 | public void CreateDatabase() 38 | { 39 | var connectionString = @"Data Source=(localdb)\MSSQLLocalDB;Integrated security=True;Application Name=DapperDal;"; 40 | var connection = new SqlConnection(connectionString); 41 | var files = new List 42 | { 43 | ReadScriptFile("CreateDatabase"), 44 | }; 45 | 46 | foreach (var setupFile in files) 47 | { 48 | connection.Execute(setupFile); 49 | } 50 | } 51 | 52 | 53 | [OneTimeTearDown] 54 | public void RunAfterAnyTests() 55 | { 56 | var connectionString = ConfigurationManager.ConnectionStrings["Default"]; 57 | var connection = new SqlConnection(connectionString.ConnectionString); 58 | var files = new List 59 | { 60 | ReadScriptFile("TruncateTable"), 61 | //ReadScriptFile("DropDatabase"), 62 | }; 63 | 64 | foreach (var setupFile in files) 65 | { 66 | connection.Execute(setupFile); 67 | } 68 | } 69 | 70 | public string ReadScriptFile(string name) 71 | { 72 | string fileName = GetType().Namespace + ".Sql." + name + ".sql"; 73 | using (Stream s = System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream(fileName)) 74 | using (StreamReader sr = new StreamReader(s)) 75 | { 76 | return sr.ReadToEnd(); 77 | } 78 | } 79 | 80 | } 81 | 82 | public class SqlServerBaseFixture 83 | { 84 | [SetUp] 85 | public virtual void Setup() 86 | { 87 | var connectionString = ConfigurationManager.ConnectionStrings["Default"]; 88 | var connection = new SqlConnection(connectionString.ConnectionString); 89 | var files = new List 90 | { 91 | ReadScriptFile("TruncateTable"), 92 | }; 93 | 94 | foreach (var setupFile in files) 95 | { 96 | connection.Execute(setupFile); 97 | } 98 | } 99 | 100 | public string ReadScriptFile(string name) 101 | { 102 | string fileName = GetType().Namespace + ".Sql." + name + ".sql"; 103 | using (Stream s = System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream(fileName)) 104 | using (StreamReader sr = new StreamReader(s)) 105 | { 106 | return sr.ReadToEnd(); 107 | } 108 | } 109 | } 110 | } -------------------------------------------------------------------------------- /test/DapperDal.Test/Mapper/AutoClassMapperFixture.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Linq; 3 | using DapperDal.Mapper; 4 | using NUnit.Framework; 5 | 6 | namespace DapperDal.Test.Mapper 7 | { 8 | [TestFixture] 9 | public class AutoClassMapperFixture 10 | { 11 | [TestFixture] 12 | public class AutoClassMapperTableName 13 | { 14 | [Test] 15 | public void Constructor_ReturnsProperName() 16 | { 17 | AutoClassMapper m = GetMapper(); 18 | Assert.AreEqual("Foo", m.TableName); 19 | } 20 | 21 | [Test] 22 | public void SettingTableName_ReturnsProperName() 23 | { 24 | AutoClassMapper m = GetMapper(); 25 | m.Table("Barz"); 26 | Assert.AreEqual("Barz", m.TableName); 27 | } 28 | 29 | [Test] 30 | public void Sets_IdPropertyToKeyWhenFirstProperty() 31 | { 32 | AutoClassMapper m = GetMapper(); 33 | var map = m.Properties.Single(p => p.KeyType == KeyType.Guid); 34 | Assert.IsTrue(map.ColumnName == "Id"); 35 | } 36 | 37 | [Test] 38 | public void Sets_IdPropertyToKeyWhenFoundInClass() 39 | { 40 | AutoClassMapper m = GetMapper(); 41 | var map = m.Properties.Single(p => p.KeyType == KeyType.Guid); 42 | Assert.IsTrue(map.ColumnName == "Id"); 43 | } 44 | 45 | [Test] 46 | public void Sets_IdFirstPropertyEndingInIdWhenNoIdPropertyFound() 47 | { 48 | AutoClassMapper m = GetMapper(); 49 | var map = m.Properties.Single(p => p.KeyType == KeyType.Guid); 50 | Assert.IsTrue(map.ColumnName == "SomeId"); 51 | } 52 | 53 | private AutoClassMapper GetMapper() where T : class 54 | { 55 | return new AutoClassMapper(); 56 | } 57 | } 58 | 59 | [TestFixture] 60 | public class CustomAutoMapperTableName 61 | { 62 | [Test] 63 | public void ReturnsProperPluralization() 64 | { 65 | CustomAutoMapper m = GetMapper(); 66 | Assert.AreEqual("Foo", m.TableName); 67 | } 68 | 69 | [Test] 70 | public void ReturnsProperResultsForExceptions() 71 | { 72 | CustomAutoMapper m = GetMapper(); 73 | Assert.AreEqual("TheFoo", m.TableName); 74 | } 75 | 76 | private CustomAutoMapper GetMapper() where T : class 77 | { 78 | return new CustomAutoMapper(); 79 | } 80 | 81 | public class CustomAutoMapper : AutoClassMapper where T : class 82 | { 83 | public override void Table(string tableName) 84 | { 85 | if (tableName.Equals("Foo2", StringComparison.CurrentCultureIgnoreCase)) 86 | { 87 | TableName = "TheFoo"; 88 | } 89 | else 90 | { 91 | base.Table(tableName); 92 | } 93 | } 94 | } 95 | } 96 | 97 | private class Foo 98 | { 99 | public Guid Id { get; set; } 100 | public Guid ParentId { get; set; } 101 | } 102 | 103 | private class Foo2 104 | { 105 | public Guid ParentId { get; set; } 106 | public Guid Id { get; set; } 107 | } 108 | 109 | 110 | private class IdIsFirst 111 | { 112 | public Guid Id { get; set; } 113 | public Guid ParentId { get; set; } 114 | } 115 | 116 | private class IdIsSecond 117 | { 118 | public Guid ParentId { get; set; } 119 | public Guid Id { get; set; } 120 | } 121 | 122 | private class IdDoesNotExist 123 | { 124 | public Guid SomeId { get; set; } 125 | public Guid ParentId { get; set; } 126 | } 127 | } 128 | } 129 | -------------------------------------------------------------------------------- /test/DapperDal.Test/Mapper/PluralizedAutoClassMapperFixture.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using DapperDal.Mapper; 3 | using NUnit.Framework; 4 | 5 | namespace DapperDal.Test.Mapper 6 | { 7 | [TestFixture] 8 | public class PluralizedAutoClassMapperFixture 9 | { 10 | [TestFixture] 11 | public class PluralizedAutoClassMapperTableName 12 | { 13 | [Test] 14 | public void ReturnsProperPluralization() 15 | { 16 | PluralizedAutoClassMapper m = GetMapper(); 17 | m.Table("robot"); 18 | Assert.AreEqual("robots", m.TableName); 19 | } 20 | 21 | [Test] 22 | public void ReturnsProperPluralizationWhenWordEndsWithY() 23 | { 24 | PluralizedAutoClassMapper m = GetMapper(); 25 | m.Table("penny"); 26 | Assert.AreEqual("pennies", m.TableName); 27 | } 28 | 29 | [Test] 30 | public void ReturnsProperPluralizationWhenWordEndsWithS() 31 | { 32 | PluralizedAutoClassMapper m = GetMapper(); 33 | m.Table("mess"); 34 | Assert.AreEqual("messes", m.TableName); 35 | } 36 | 37 | [Test] 38 | public void ReturnsProperPluralizationWhenWordEndsWithF() 39 | { 40 | PluralizedAutoClassMapper m = GetMapper(); 41 | m.Table("life"); 42 | Assert.AreEqual("lives", m.TableName); 43 | } 44 | 45 | [Test] 46 | public void ReturnsProperPluralizationWhenWordWithFe() 47 | { 48 | PluralizedAutoClassMapper m = GetMapper(); 49 | m.Table("leaf"); 50 | Assert.AreEqual("leaves", m.TableName); 51 | } 52 | 53 | [Test] 54 | public void ReturnsProperPluralizationWhenWordContainsF() 55 | { 56 | PluralizedAutoClassMapper m = GetMapper(); 57 | m.Table("profile"); 58 | Assert.AreEqual("profiles", m.TableName); 59 | } 60 | 61 | [Test] 62 | public void ReturnsProperPluralizationWhenWordContainsFe() 63 | { 64 | PluralizedAutoClassMapper m = GetMapper(); 65 | m.Table("effect"); 66 | Assert.AreEqual("effects", m.TableName); 67 | } 68 | 69 | private PluralizedAutoClassMapper GetMapper() where T : class 70 | { 71 | return new PluralizedAutoClassMapper(); 72 | } 73 | } 74 | 75 | [TestFixture] 76 | public class CustomPluralizedMapperTableName 77 | { 78 | [Test] 79 | public void ReturnsProperPluralization() 80 | { 81 | CustomPluralizedMapper m = GetMapper(); 82 | m.Table("Dog"); 83 | Assert.AreEqual("Dogs", m.TableName); 84 | } 85 | 86 | [Test] 87 | public void ReturnsProperResultsForExceptions() 88 | { 89 | CustomPluralizedMapper m = GetMapper(); 90 | m.Table("Person"); 91 | Assert.AreEqual("People", m.TableName); 92 | } 93 | 94 | private CustomPluralizedMapper GetMapper() where T : class 95 | { 96 | return new CustomPluralizedMapper(); 97 | } 98 | 99 | public class CustomPluralizedMapper : PluralizedAutoClassMapper where T : class 100 | { 101 | public override void Table(string tableName) 102 | { 103 | if (tableName.Equals("Person", StringComparison.CurrentCultureIgnoreCase)) 104 | { 105 | TableName = "People"; 106 | } 107 | else 108 | { 109 | base.Table(tableName); 110 | } 111 | } 112 | } 113 | } 114 | 115 | private class Foo 116 | { 117 | } 118 | } 119 | } 120 | -------------------------------------------------------------------------------- /test/DapperDal.Test/Mapper/PropertyMapFixture.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Linq.Expressions; 3 | using System.Reflection; 4 | using DapperDal.Mapper; 5 | using DapperDal.Utils; 6 | using NUnit.Framework; 7 | 8 | namespace DapperDal.Test.Mapper 9 | { 10 | [TestFixture] 11 | public class PropertyMapFixture 12 | { 13 | private class Foo 14 | { 15 | public int Bar { get; set; } 16 | public string Baz { get; set; } 17 | } 18 | 19 | [Test] 20 | public void PropertyMap_Constructor_Sets_Name_And_ColumnName_Property_From_PropertyInfo() 21 | { 22 | Expression> expression = f => f.Bar; 23 | var pi = ReflectionHelper.GetProperty(expression) as PropertyInfo; 24 | PropertyMap pm = new PropertyMap(pi); 25 | Assert.AreEqual("Bar", pm.Name); 26 | Assert.AreEqual("Bar", pm.ColumnName); 27 | } 28 | 29 | [Test] 30 | public void PropertyMap_Column_Sets_ColumnName_But_Does_Not_Change_Name() 31 | { 32 | Expression> expression = f => f.Baz; 33 | var pi = ReflectionHelper.GetProperty(expression) as PropertyInfo; 34 | PropertyMap pm = new PropertyMap(pi); 35 | pm.Column("X"); 36 | Assert.AreEqual("Baz", pm.Name); 37 | Assert.AreEqual("X", pm.ColumnName); 38 | } 39 | 40 | [Test] 41 | public void PropertyMap_Key_Sets_KeyType() 42 | { 43 | Expression> expression = f => f.Baz; 44 | var pi = ReflectionHelper.GetProperty(expression) as PropertyInfo; 45 | PropertyMap pm = new PropertyMap(pi); 46 | pm.Column("X").Key(KeyType.Identity); 47 | Assert.AreEqual("Baz", pm.Name); 48 | Assert.AreEqual("X", pm.ColumnName); 49 | Assert.AreEqual(KeyType.Identity, pm.KeyType); 50 | } 51 | } 52 | } -------------------------------------------------------------------------------- /test/DapperDal.Test/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.CompilerServices; 3 | using System.Runtime.InteropServices; 4 | 5 | // 有关程序集的一般信息由以下 6 | // 控制。更改这些特性值可修改 7 | // 与程序集关联的信息。 8 | [assembly: AssemblyTitle("DapperDal.Test")] 9 | [assembly: AssemblyDescription("")] 10 | [assembly: AssemblyConfiguration("")] 11 | [assembly: AssemblyCompany("")] 12 | [assembly: AssemblyProduct("DapperDal.Test")] 13 | [assembly: AssemblyCopyright("Copyright © 2017")] 14 | [assembly: AssemblyTrademark("")] 15 | [assembly: AssemblyCulture("")] 16 | 17 | // 将 ComVisible 设置为 false 会使此程序集中的类型 18 | //对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型 19 | //请将此类型的 ComVisible 特性设置为 true。 20 | [assembly: ComVisible(false)] 21 | 22 | // 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID 23 | [assembly: Guid("8bf8684b-e2f2-43a3-b5c7-b9c49f1810c5")] 24 | 25 | // 程序集的版本信息由下列四个值组成: 26 | // 27 | // 主版本 28 | // 次版本 29 | // 生成号 30 | // 修订号 31 | // 32 | // 可以指定所有值,也可以使用以下所示的 "*" 预置版本号和修订号 33 | //通过使用 "*",如下所示: 34 | // [assembly: AssemblyVersion("1.0.*")] 35 | [assembly: AssemblyVersion("1.0.0.0")] 36 | [assembly: AssemblyFileVersion("1.0.0.0")] 37 | -------------------------------------------------------------------------------- /test/DapperDal.Test/ReflectionHelperFixture.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Linq.Expressions; 3 | using DapperDal.Utils; 4 | using NUnit.Framework; 5 | 6 | namespace DapperDal.Test 7 | { 8 | [TestFixture] 9 | public class ReflectionHelperFixture 10 | { 11 | private class Foo 12 | { 13 | public int Bar { get; set; } 14 | public string Baz { get; set; } 15 | } 16 | 17 | [Test] 18 | public void GetProperty_Returns_MemberInfo_For_Correct_Property() 19 | { 20 | Expression> expression = f => f.Bar; 21 | var m = ReflectionHelper.GetProperty(expression); 22 | Assert.AreEqual("Bar", m.Name); 23 | } 24 | 25 | [Test] 26 | public void GetObjectValues_Returns_Dictionary_With_Property_Value_Pairs() 27 | { 28 | Foo f = new Foo { Bar = 3, Baz = "Yum" }; 29 | 30 | var dictionary = ReflectionHelper.GetObjectValues(f); 31 | Assert.AreEqual(3, dictionary["Bar"]); 32 | Assert.AreEqual("Yum", dictionary["Baz"]); 33 | } 34 | 35 | [Test] 36 | public void GetObjectValues_Returns_Empty_Dictionary_When_Null_Object_Provided() 37 | { 38 | var dictionary = ReflectionHelper.GetObjectValues(null); 39 | Assert.AreEqual(0, dictionary.Count); 40 | } 41 | } 42 | } -------------------------------------------------------------------------------- /test/DapperDal.Test/Sql/SqlServerDialectFixture.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Globalization; 4 | using System.Threading; 5 | using DapperDal.Sql; 6 | using DapperDal.Test.Helpers; 7 | using NUnit.Framework; 8 | 9 | namespace DapperDal.Test.Sql 10 | { 11 | [TestFixture] 12 | public class SqlServerDialectFixture 13 | { 14 | public abstract class SqlServerDialectFixtureBase 15 | { 16 | protected SqlServerDialect Dialect; 17 | 18 | [SetUp] 19 | public void Setup() 20 | { 21 | Thread.CurrentThread.CurrentUICulture = new CultureInfo("en-us"); 22 | 23 | Dialect = new SqlServerDialect(); 24 | } 25 | } 26 | 27 | [TestFixture] 28 | public class Properties : SqlServerDialectFixtureBase 29 | { 30 | [Test] 31 | public void CheckSettings() 32 | { 33 | Assert.AreEqual('[', Dialect.OpenQuote); 34 | Assert.AreEqual(']', Dialect.CloseQuote); 35 | Assert.AreEqual(";" + Environment.NewLine, Dialect.BatchSeperator); 36 | Assert.AreEqual('@', Dialect.ParameterPrefix); 37 | Assert.IsTrue(Dialect.SupportsMultipleStatements); 38 | } 39 | } 40 | 41 | [TestFixture] 42 | public class GetPagingSqlMethod : SqlServerDialectFixtureBase 43 | { 44 | [Test] 45 | public void NullSql_ThrowsException() 46 | { 47 | var ex = Assert.Throws(() => Dialect.GetPagingSql(null, 0, 10, new Dictionary())); 48 | Assert.AreEqual("SQL", ex.ParamName); 49 | StringAssert.Contains("cannot be null", ex.Message); 50 | } 51 | 52 | [Test] 53 | public void EmptySql_ThrowsException() 54 | { 55 | var ex = Assert.Throws(() => Dialect.GetPagingSql(string.Empty, 0, 10, new Dictionary())); 56 | Assert.AreEqual("SQL", ex.ParamName); 57 | StringAssert.Contains("cannot be null", ex.Message); 58 | } 59 | 60 | [Test] 61 | public void NullParameters_ThrowsException() 62 | { 63 | var ex = Assert.Throws(() => Dialect.GetPagingSql("SELECT [schema].[column] FROM [schema].[table]", 0, 10, null)); 64 | Assert.AreEqual("Parameters", ex.ParamName); 65 | StringAssert.Contains("cannot be null", ex.Message); 66 | } 67 | 68 | [Test] 69 | public void Select_ReturnsSql() 70 | { 71 | var parameters = new Dictionary(); 72 | string sql = "SELECT TOP(10) [_proj].[column] FROM (SELECT ROW_NUMBER() OVER(ORDER BY CURRENT_TIMESTAMP) AS [_row_number], [column] FROM [schema].[table]) [_proj] WHERE [_proj].[_row_number] >= @_pageStartRow ORDER BY [_proj].[_row_number]"; 73 | var result = Dialect.GetPagingSql("SELECT [column] FROM [schema].[table]", 0, 10, parameters); 74 | Assert.AreEqual(sql, result); 75 | Assert.AreEqual(1, parameters.Count); 76 | Assert.AreEqual(parameters["@_pageStartRow"], 1); 77 | } 78 | 79 | [Test] 80 | public void SelectDistinct_ReturnsSql() 81 | { 82 | var parameters = new Dictionary(); 83 | string sql = "SELECT TOP(10) [_proj].[column] FROM (SELECT DISTINCT ROW_NUMBER() OVER(ORDER BY CURRENT_TIMESTAMP) AS [_row_number], [column] FROM [schema].[table]) [_proj] WHERE [_proj].[_row_number] >= @_pageStartRow ORDER BY [_proj].[_row_number]"; 84 | var result = Dialect.GetPagingSql("SELECT DISTINCT [column] FROM [schema].[table]", 0, 10, parameters); 85 | Assert.AreEqual(sql, result); 86 | Assert.AreEqual(1, parameters.Count); 87 | Assert.AreEqual(parameters["@_pageStartRow"], 1); 88 | } 89 | 90 | [Test] 91 | public void SelectOrderBy_ReturnsSql() 92 | { 93 | var parameters = new Dictionary(); 94 | string sql = "SELECT TOP(10) [_proj].[column] FROM (SELECT ROW_NUMBER() OVER(ORDER BY [column] DESC) AS [_row_number], [column] FROM [schema].[table]) [_proj] WHERE [_proj].[_row_number] >= @_pageStartRow ORDER BY [_proj].[_row_number]"; 95 | var result = Dialect.GetPagingSql("SELECT [column] FROM [schema].[table] ORDER BY [column] DESC", 0, 10, parameters); 96 | Assert.AreEqual(sql, result); 97 | Assert.AreEqual(1, parameters.Count); 98 | Assert.AreEqual(parameters["@_pageStartRow"], 1); 99 | } 100 | } 101 | 102 | [TestFixture] 103 | public class GetOrderByClauseMethod : SqlServerDialectFixtureBase 104 | { 105 | [Test] 106 | public void NoOrderBy_Returns() 107 | { 108 | var result = Dialect.TestProtected().RunMethod("GetOrderByClause", "SELECT * FROM Table"); 109 | Assert.IsNull(result); 110 | } 111 | 112 | [Test] 113 | public void OrderBy_ReturnsItemsAfterClause() 114 | { 115 | var result = Dialect.TestProtected().RunMethod("GetOrderByClause", "SELECT * FROM Table ORDER BY Column1 ASC, Column2 DESC"); 116 | Assert.AreEqual("ORDER BY Column1 ASC, Column2 DESC", result); 117 | } 118 | 119 | [Test] 120 | public void OrderByWithWhere_ReturnsOnlyOrderBy() 121 | { 122 | var result = Dialect.TestProtected().RunMethod("GetOrderByClause", "SELECT * FROM Table ORDER BY Column1 ASC, Column2 DESC WHERE Column1 = 'value'"); 123 | Assert.AreEqual("ORDER BY Column1 ASC, Column2 DESC", result); 124 | } 125 | } 126 | } 127 | } -------------------------------------------------------------------------------- /test/DapperDal.Test/packages.config: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /toc.yml: -------------------------------------------------------------------------------- 1 | - name: Home 2 | href: README.md 3 | - name: Api Documentation 4 | href: api/ 5 | topicHref: api/index.md 6 | --------------------------------------------------------------------------------