├── .gitignore ├── E.EntityFrameworkCore.Extensions.sln ├── LICENSE ├── README.md ├── src └── E.EntityFrameworkCore.Extensions │ ├── CheckUseDefaultStringMaxLenghtResult.cs │ ├── ColumnNameCaseType.cs │ ├── E.EntityFrameworkCore.Extensions.csproj │ ├── E.EntityFrameworkCore.Extensions.xml │ └── EntityFrameworkCoreTableViewExtensions.cs └── test └── TestWebApp ├── Controllers └── HomeController.cs ├── Database ├── BloggingContext.cs └── Models │ └── Model.cs ├── Program.cs ├── Startup.cs ├── TestWebApp.csproj ├── appsettings.Development.json └── appsettings.json /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | ## 4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore 5 | 6 | # User-specific files 7 | *.suo 8 | *.user 9 | *.userosscache 10 | *.sln.docstates 11 | 12 | # User-specific files (MonoDevelop/Xamarin Studio) 13 | *.userprefs 14 | 15 | # Build results 16 | [Dd]ebug/ 17 | [Dd]ebugPublic/ 18 | [Rr]elease/ 19 | [Rr]eleases/ 20 | x64/ 21 | x86/ 22 | bld/ 23 | [Bb]in/ 24 | [Oo]bj/ 25 | [Ll]og/ 26 | 27 | # Visual Studio 2015/2017 cache/options directory 28 | .vs/ 29 | # Uncomment if you have tasks that create the project's static files in wwwroot 30 | #wwwroot/ 31 | 32 | # Visual Studio 2017 auto generated files 33 | Generated\ Files/ 34 | 35 | # MSTest test Results 36 | [Tt]est[Rr]esult*/ 37 | [Bb]uild[Ll]og.* 38 | 39 | # NUNIT 40 | *.VisualState.xml 41 | TestResult.xml 42 | 43 | # Build Results of an ATL Project 44 | [Dd]ebugPS/ 45 | [Rr]eleasePS/ 46 | dlldata.c 47 | 48 | # Benchmark Results 49 | BenchmarkDotNet.Artifacts/ 50 | 51 | # .NET Core 52 | project.lock.json 53 | project.fragment.lock.json 54 | artifacts/ 55 | **/Properties/launchSettings.json 56 | 57 | # StyleCop 58 | StyleCopReport.xml 59 | 60 | # Files built by Visual Studio 61 | *_i.c 62 | *_p.c 63 | *_i.h 64 | *.ilk 65 | *.meta 66 | *.obj 67 | *.iobj 68 | *.pch 69 | *.pdb 70 | *.ipdb 71 | *.pgc 72 | *.pgd 73 | *.rsp 74 | *.sbr 75 | *.tlb 76 | *.tli 77 | *.tlh 78 | *.tmp 79 | *.tmp_proj 80 | *.log 81 | *.vspscc 82 | *.vssscc 83 | .builds 84 | *.pidb 85 | *.svclog 86 | *.scc 87 | 88 | # Chutzpah Test files 89 | _Chutzpah* 90 | 91 | # Visual C++ cache files 92 | ipch/ 93 | *.aps 94 | *.ncb 95 | *.opendb 96 | *.opensdf 97 | *.sdf 98 | *.cachefile 99 | *.VC.db 100 | *.VC.VC.opendb 101 | 102 | # Visual Studio profiler 103 | *.psess 104 | *.vsp 105 | *.vspx 106 | *.sap 107 | 108 | # Visual Studio Trace Files 109 | *.e2e 110 | 111 | # TFS 2012 Local Workspace 112 | $tf/ 113 | 114 | # Guidance Automation Toolkit 115 | *.gpState 116 | 117 | # ReSharper is a .NET coding add-in 118 | _ReSharper*/ 119 | *.[Rr]e[Ss]harper 120 | *.DotSettings.user 121 | 122 | # JustCode is a .NET coding add-in 123 | .JustCode 124 | 125 | # TeamCity is a build add-in 126 | _TeamCity* 127 | 128 | # DotCover is a Code Coverage Tool 129 | *.dotCover 130 | 131 | # AxoCover is a Code Coverage Tool 132 | .axoCover/* 133 | !.axoCover/settings.json 134 | 135 | # Visual Studio code coverage results 136 | *.coverage 137 | *.coveragexml 138 | 139 | # NCrunch 140 | _NCrunch_* 141 | .*crunch*.local.xml 142 | nCrunchTemp_* 143 | 144 | # MightyMoose 145 | *.mm.* 146 | AutoTest.Net/ 147 | 148 | # Web workbench (sass) 149 | .sass-cache/ 150 | 151 | # Installshield output folder 152 | [Ee]xpress/ 153 | 154 | # DocProject is a documentation generator add-in 155 | DocProject/buildhelp/ 156 | DocProject/Help/*.HxT 157 | DocProject/Help/*.HxC 158 | DocProject/Help/*.hhc 159 | DocProject/Help/*.hhk 160 | DocProject/Help/*.hhp 161 | DocProject/Help/Html2 162 | DocProject/Help/html 163 | 164 | # Click-Once directory 165 | publish/ 166 | 167 | # Publish Web Output 168 | *.[Pp]ublish.xml 169 | *.azurePubxml 170 | # Note: Comment the next line if you want to checkin your web deploy settings, 171 | # but database connection strings (with potential passwords) will be unencrypted 172 | *.pubxml 173 | *.publishproj 174 | 175 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 176 | # checkin your Azure Web App publish settings, but sensitive information contained 177 | # in these scripts will be unencrypted 178 | PublishScripts/ 179 | 180 | # NuGet Packages 181 | *.nupkg 182 | # The packages folder can be ignored because of Package Restore 183 | **/[Pp]ackages/* 184 | # except build/, which is used as an MSBuild target. 185 | !**/[Pp]ackages/build/ 186 | # Uncomment if necessary however generally it will be regenerated when needed 187 | #!**/[Pp]ackages/repositories.config 188 | # NuGet v3's project.json files produces more ignorable files 189 | *.nuget.props 190 | *.nuget.targets 191 | 192 | # Microsoft Azure Build Output 193 | csx/ 194 | *.build.csdef 195 | 196 | # Microsoft Azure Emulator 197 | ecf/ 198 | rcf/ 199 | 200 | # Windows Store app package directories and files 201 | AppPackages/ 202 | BundleArtifacts/ 203 | Package.StoreAssociation.xml 204 | _pkginfo.txt 205 | *.appx 206 | 207 | # Visual Studio cache files 208 | # files ending in .cache can be ignored 209 | *.[Cc]ache 210 | # but keep track of directories ending in .cache 211 | !*.[Cc]ache/ 212 | 213 | # Others 214 | ClientBin/ 215 | ~$* 216 | *~ 217 | *.dbmdl 218 | *.dbproj.schemaview 219 | *.jfm 220 | *.pfx 221 | *.publishsettings 222 | orleans.codegen.cs 223 | 224 | # Including strong name files can present a security risk 225 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 226 | #*.snk 227 | 228 | # Since there are multiple workflows, uncomment next line to ignore bower_components 229 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 230 | #bower_components/ 231 | 232 | # RIA/Silverlight projects 233 | Generated_Code/ 234 | 235 | # Backup & report files from converting an old project file 236 | # to a newer Visual Studio version. Backup files are not needed, 237 | # because we have git ;-) 238 | _UpgradeReport_Files/ 239 | Backup*/ 240 | UpgradeLog*.XML 241 | UpgradeLog*.htm 242 | ServiceFabricBackup/ 243 | *.rptproj.bak 244 | 245 | # SQL Server files 246 | *.mdf 247 | *.ldf 248 | *.ndf 249 | 250 | # Business Intelligence projects 251 | *.rdl.data 252 | *.bim.layout 253 | *.bim_*.settings 254 | *.rptproj.rsuser 255 | 256 | # Microsoft Fakes 257 | FakesAssemblies/ 258 | 259 | # GhostDoc plugin setting file 260 | *.GhostDoc.xml 261 | 262 | # Node.js Tools for Visual Studio 263 | .ntvs_analysis.dat 264 | node_modules/ 265 | 266 | # Visual Studio 6 build log 267 | *.plg 268 | 269 | # Visual Studio 6 workspace options file 270 | *.opt 271 | 272 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 273 | *.vbw 274 | 275 | # Visual Studio LightSwitch build output 276 | **/*.HTMLClient/GeneratedArtifacts 277 | **/*.DesktopClient/GeneratedArtifacts 278 | **/*.DesktopClient/ModelManifest.xml 279 | **/*.Server/GeneratedArtifacts 280 | **/*.Server/ModelManifest.xml 281 | _Pvt_Extensions 282 | 283 | # Paket dependency manager 284 | .paket/paket.exe 285 | paket-files/ 286 | 287 | # FAKE - F# Make 288 | .fake/ 289 | 290 | # JetBrains Rider 291 | .idea/ 292 | *.sln.iml 293 | 294 | # CodeRush 295 | .cr/ 296 | 297 | # Python Tools for Visual Studio (PTVS) 298 | __pycache__/ 299 | *.pyc 300 | 301 | # Cake - Uncomment if you are using it 302 | # tools/** 303 | # !tools/packages.config 304 | 305 | # Tabs Studio 306 | *.tss 307 | 308 | # Telerik's JustMock configuration file 309 | *.jmconfig 310 | 311 | # BizTalk build output 312 | *.btp.cs 313 | *.btm.cs 314 | *.odx.cs 315 | *.xsd.cs 316 | 317 | # OpenCover UI analysis results 318 | OpenCover/ 319 | 320 | # Azure Stream Analytics local run output 321 | ASALocalRun/ 322 | 323 | # MSBuild Binary and Structured Log 324 | *.binlog 325 | 326 | # NVidia Nsight GPU debugger configuration file 327 | *.nvuser 328 | 329 | # MFractors (Xamarin productivity tool) working folder 330 | .mfractor/ 331 | -------------------------------------------------------------------------------- /E.EntityFrameworkCore.Extensions.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 16 4 | VisualStudioVersion = 16.0.28729.10 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{6ABC4131-688B-4600-BAD7-28FF7AD96270}" 7 | EndProject 8 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "test", "test", "{5094A6B8-0C93-4597-A504-32186D2EC1AD}" 9 | EndProject 10 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "E.EntityFrameworkCore.Extensions", "src\E.EntityFrameworkCore.Extensions\E.EntityFrameworkCore.Extensions.csproj", "{7C10C016-5B7C-4EF5-AC59-2B6DFC11F0C9}" 11 | EndProject 12 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TestWebApp", "test\TestWebApp\TestWebApp.csproj", "{8B3AE71E-5136-4EF5-A3FD-5A66C5F71108}" 13 | EndProject 14 | Global 15 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 16 | Debug|Any CPU = Debug|Any CPU 17 | Release|Any CPU = Release|Any CPU 18 | EndGlobalSection 19 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 20 | {7C10C016-5B7C-4EF5-AC59-2B6DFC11F0C9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 21 | {7C10C016-5B7C-4EF5-AC59-2B6DFC11F0C9}.Debug|Any CPU.Build.0 = Debug|Any CPU 22 | {7C10C016-5B7C-4EF5-AC59-2B6DFC11F0C9}.Release|Any CPU.ActiveCfg = Release|Any CPU 23 | {7C10C016-5B7C-4EF5-AC59-2B6DFC11F0C9}.Release|Any CPU.Build.0 = Release|Any CPU 24 | {8B3AE71E-5136-4EF5-A3FD-5A66C5F71108}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 25 | {8B3AE71E-5136-4EF5-A3FD-5A66C5F71108}.Debug|Any CPU.Build.0 = Debug|Any CPU 26 | {8B3AE71E-5136-4EF5-A3FD-5A66C5F71108}.Release|Any CPU.ActiveCfg = Release|Any CPU 27 | {8B3AE71E-5136-4EF5-A3FD-5A66C5F71108}.Release|Any CPU.Build.0 = Release|Any CPU 28 | EndGlobalSection 29 | GlobalSection(SolutionProperties) = preSolution 30 | HideSolutionNode = FALSE 31 | EndGlobalSection 32 | GlobalSection(NestedProjects) = preSolution 33 | {7C10C016-5B7C-4EF5-AC59-2B6DFC11F0C9} = {6ABC4131-688B-4600-BAD7-28FF7AD96270} 34 | {8B3AE71E-5136-4EF5-A3FD-5A66C5F71108} = {5094A6B8-0C93-4597-A504-32186D2EC1AD} 35 | EndGlobalSection 36 | GlobalSection(ExtensibilityGlobals) = postSolution 37 | SolutionGuid = {A0714636-DF3D-4A82-BC01-940F75C830D1} 38 | EndGlobalSection 39 | EndGlobal 40 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ## E.EntityFrameworkCore.Extensions 2 | --- 3 | 4 | 此仓库已停止更新,请移步到此处: [链接](https://github.com/rivenfx/EntityFrameworkCore) 5 | 6 | --- 7 | EntityFrameworkCore 的扩展库 8 | 9 | [![NuGet Version](https://img.shields.io/nuget/v/E.EntityFrameworkCore.Extensions.svg?style=flat)](https://www.nuget.org/packages/E.EntityFrameworkCore.Extensions/) 10 | 11 | [![NuGet Downloads](https://img.shields.io/nuget/dt/E.EntityFrameworkCore.Extensions.svg?style=flat)](https://www.nuget.org/packages/E.EntityFrameworkCore.Extensions/) 12 | 13 | ## 功能 14 | --- 15 | **目前已经实现的功能**: 16 | * PostgreSql DbSet 表名、视图名、列名自动处理为小写 17 | * Oracle DbSet 表名、视图名、列名自动处理为大写 18 | * 自定义 DbSet 校验处理函数 19 | * 自定义 DbQuery 校验处理函数 20 | * 自定义 Column(Field) 校验处理函数 21 | * 自定义列名长度,自动进行裁剪 22 | * 自动跳过处理 DbContext 程序集中已实现的 IEntityTypeConfiguration 23 | * 增加是否使用 DbSet/DbQuery 名称作为 表名称/视图名称 选项 24 | * 增加字符串列设置默认数据长度 校验函数 25 | 26 | 27 | ## 基本用法 28 | 29 | ### 1. 引入nuget包 30 | * dotnet cli 31 | 32 | `dotnet add package E.EntityFrameworkCore.Extensions` 33 | 34 | * nuget package manager 35 | 36 | `Install-Package E.EntityFrameworkCore.Extensions` 37 | 38 | ### 2. 配置 DbContext 39 | 40 | * 重写 DbContext的 OnModelCreating 函数 41 | * 引入命名空间 `using E;` 42 | 43 | 44 | ### 3. 配置 E.EntityFrameworkCore.Extensions 45 | ***以下代码均处于 OnModelCreating 函数中*** 46 | 47 | **PostgreSql** 48 | ``` 49 | base.OnModelCreating(modelBuilder); 50 | 51 | // 禁用 使用DbSet名称作为表名和视图名称,优先读Table标记,其次类名 52 | E.EntityFrameworkCoreTableViewExtensions.UseDbSetNameToTableName = false; 53 | 54 | // 设置小写 55 | E.EntityFrameworkCoreTableViewExtensions.SetCaseType(modelBuilder, ColumnNameCaseType.Lower); 56 | 57 | // 自定义要处理的字段类型,较多,此处不贴完整 58 | E.EntityFrameworkCoreTableViewExtensions.DbMapTypes.Add("System.String[]"); 59 | E.EntityFrameworkCoreTableViewExtensions.DbMapTypes.Add("System.Boolean[]"); 60 | E.EntityFrameworkCoreTableViewExtensions.DbMapTypes.Add("System.Int32[]"); 61 | 62 | // 处理此数据库上下文类型中 DbSet 63 | // 参数为 true,则 自动跳过处理 DbContext 程序集中已实现的 IEntityTypeConfiguration 的 DbSet 64 | modelBuilder.CaseAllDbSetNameAndColumnName(/* true */); 65 | 66 | ``` 67 | 68 | **Oracle** 69 | ``` 70 | base.OnModelCreating(modelBuilder); 71 | 72 | 73 | // 禁用 使用DbSet名称作为表名和视图名称,优先读Table标记,其次类名 74 | E.EntityFrameworkCoreTableViewExtensions.UseDbSetNameToTableName = false; 75 | 76 | // 设置大写 77 | E.EntityFrameworkCoreTableViewExtensions.SetCaseType(modelBuilder, ColumnNameCaseType.Upper); 78 | 79 | // 使用列名长度限制,最大30 80 | E.EntityFrameworkCoreTableViewExtensions.UseColumnNameMaxLength = true; 81 | E.EntityFrameworkCoreTableViewExtensions.ColumnNameMaxLength = 30; 82 | 83 | // 使用默认字符串长度 84 | E.EntityFrameworkCoreTableViewExtensions.UseDefaultStringMaxLength = true; 85 | E.EntityFrameworkCoreTableViewExtensions.DefaultStringMaxLength = 256; 86 | // 自定义 字符串列数据长度 是否设置默认长度 校验函数 87 | E.EntityFrameworkCoreTableViewExtensions.CheckUseDefaultStringMaxLength = (type, prop) => 88 | { 89 | 90 | var checkResult = new CheckUseDefaultStringMaxLenghtResult(); 91 | 92 | // 如果实体的命名空间为 TestWebApp.Database.Models 则设置长度为200 93 | if (type.Namespace.StartsWith("TestWebApp.Database.Models")) 94 | { 95 | checkResult.Success = true; 96 | checkResult.MaxLength = 200; 97 | } 98 | 99 | 100 | return checkResult; 101 | }; 102 | 103 | // 处理此数据库上下文类型中 DbSet 104 | // 参数为 true,则 自动跳过处理 DbContext 程序集中已实现的 IEntityTypeConfiguration 的 DbSet 105 | modelBuilder.CaseAllDbSetNameAndColumnName(/* true */); 106 | 107 | ``` 108 | 109 | ## 自定义校验处理函数 110 | ***以下代码均处于 OnModelCreating 函数中*** 111 | ``` 112 | // DbSet Check 113 | E.EntityFrameworkCoreTableViewExtensions.DbSetCheck = (info) => 114 | { 115 | // 你的校验逻辑 116 | return true;// or false 117 | }; 118 | 119 | // Column Chcek 120 | E.EntityFrameworkCoreTableViewExtensions.ColumnCheck = (info) => 121 | { 122 | // 你的校验逻辑 123 | return true;// or false 124 | }; 125 | 126 | ``` 127 | 128 | -------------------------------------------------------------------------------- /src/E.EntityFrameworkCore.Extensions/CheckUseDefaultStringMaxLenghtResult.cs: -------------------------------------------------------------------------------- 1 | namespace E 2 | { 3 | /// 4 | /// 检查字符串类型字段长度限制返回结果 5 | /// 6 | public class CheckUseDefaultStringMaxLenghtResult 7 | { 8 | /// 9 | /// 默认构造函数 10 | /// 11 | public CheckUseDefaultStringMaxLenghtResult() 12 | { 13 | 14 | } 15 | 16 | /// 17 | /// 构造函数 18 | /// 19 | /// 是否成功 20 | /// 最大长度 21 | public CheckUseDefaultStringMaxLenghtResult(bool success, int? maxLength = null) 22 | { 23 | this.Success = success; 24 | this.MaxLength = maxLength; 25 | } 26 | 27 | /// 28 | /// 是否成功 29 | /// 30 | public bool Success { get; set; } 31 | 32 | /// 33 | /// 自定义长度 34 | /// 35 | public int? MaxLength { get; set; } 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /src/E.EntityFrameworkCore.Extensions/ColumnNameCaseType.cs: -------------------------------------------------------------------------------- 1 | namespace E 2 | { 3 | /// 4 | /// 列转换类型 5 | /// 6 | public enum ColumnNameCaseType 7 | { 8 | /// 9 | /// 默认不做处理 10 | /// 11 | Default = 0, 12 | /// 13 | /// 转大写 14 | /// 15 | Upper = 1, 16 | /// 17 | /// 转小写 18 | /// 19 | Lower = 2, 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/E.EntityFrameworkCore.Extensions/E.EntityFrameworkCore.Extensions.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | netstandard2.0 5 | E 6 | true 7 | false 8 | 0.1.0 9 | staneee 10 | 11 | zh-CN 12 | staneee 13 | https://github.com/staneee/E.EntityFrameworkCore.Extensions 14 | github 15 | https://github.com/staneee/E.EntityFrameworkCore.Extensions 16 | E,Data,EntityFrameworkCore,EFCore,Core 17 | Extension to the EntityFrameworkCore API 18 | 19 | 20 | 21 | ./E.EntityFrameworkCore.Extensions.xml 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | -------------------------------------------------------------------------------- /src/E.EntityFrameworkCore.Extensions/E.EntityFrameworkCore.Extensions.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | E.EntityFrameworkCore.Extensions 5 | 6 | 7 | 8 | 9 | 检查字符串类型字段长度限制返回结果 10 | 11 | 12 | 13 | 14 | 默认构造函数 15 | 16 | 17 | 18 | 19 | 构造函数 20 | 21 | 是否成功 22 | 最大长度 23 | 24 | 25 | 26 | 是否成功 27 | 28 | 29 | 30 | 31 | 自定义长度 32 | 33 | 34 | 35 | 36 | 列转换类型 37 | 38 | 39 | 40 | 41 | 默认不做处理 42 | 43 | 44 | 45 | 46 | 转大写 47 | 48 | 49 | 50 | 51 | 转小写 52 | 53 | 54 | 55 | 56 | EntityFrameworkCore 表和视图的扩展 57 | [Extension to the EntityFrameworkCore table and view] 58 | 59 | 60 | 61 | 62 | 列名大小写转换类型,默认为不转换 63 | [Enables uppercase, false by default, and lowercase by default] 64 | 65 | 66 | 67 | 68 | 启用设置字符串默认长度,默认为 false 69 | [Sets the default length of the string to false by default] 70 | 71 | 72 | 73 | 74 | 默认字符串使用的长度 (默认 512) 75 | [The length of the default string used (default 512)] 76 | 77 | 78 | 79 | 80 | 外部自定义属性映射到字段检查方法 81 | [External custom attributes map to field inspection methods] 82 | 83 | 84 | 85 | 86 | 所有允许映射到数据库的字段类型(谨慎更改) 87 | [All field types that allow mapping to the database (changed carefully)] 88 | 89 | 90 | 91 | 92 | DbSet 类型字符串(谨慎修改) 93 | [DbSet type string (carefully modified)] 94 | 95 | 96 | 97 | 98 | 外部自定义 DbSet 是否处理的检查方法 99 | [External custom DbSet whether to handle the check method] 100 | 101 | 102 | 103 | 104 | 启用列名最大长度限制,默认为fasle 105 | [Enables the maximum length limit for column names, which is fasle by default] 106 | 107 | 108 | 109 | 110 | 列名最大长度,默认30 111 | [Column name maximum length, default 30] 112 | 113 | 114 | 115 | 116 | IEntityTypeConfiguration 接口字符串 117 | 118 | 119 | 120 | 121 | 使用DbSet名称为数据库表名称 122 | 123 | 124 | 125 | 126 | 使用DbQuery名称作为数据库视图名称 127 | 128 | 129 | 130 | 131 | 外部自定义 设置字符串类型列数据长度 是否处理的检查方法 132 | 133 | 134 | 135 | 136 | 表特性类型 137 | [Table property type] 138 | 139 | 140 | 141 | 142 | 列特性类型 143 | [Column attribute type] 144 | 145 | 146 | 147 | 148 | 不映射特性类型 149 | [Attribute types are not mapped] 150 | 151 | 152 | 153 | 154 | 字符串类型 155 | [String type] 156 | 157 | 158 | 159 | 160 | 字符串长度特性类型 161 | [String length attribute type] 162 | 163 | 164 | 165 | 166 | 实现 IEntityTypeConfiguration 类型的集合 167 | 168 | 169 | 170 | 171 | 设置DbContext的所有DbSet 对应的 表名和列名 172 | [Set the table and column names for all dbsets of the DbContext] 173 | 174 | 175 | 176 | 177 | 178 | 179 | 180 | 181 | 自动将表名和列名转换大小写,部分特殊列需要手动处理 182 | [Automatically converts table and column names to case, and some special columns need to be handled manually] 183 | 184 | 185 | 186 | 187 | 188 | 189 | 190 | 191 | 设置表名和Schema [Set the table name and Schema] 192 | 优先级: 193 | * 传入的 tableName 和 schema 194 | * 实体标记的 TableAttribute 195 | * 实体名称, schema 不设置 196 | 197 | 198 | 199 | 200 | 201 | 202 | 203 | 204 | 自动将视图名和列名转换大小写,部分特殊列需要手动处理 205 | [Automatically converts view and column names to case, and some special columns need to be handled manually] 206 | 207 | 208 | 209 | 210 | 211 | 212 | 213 | 214 | 设置视图名称和Schema [Set the view name and Schema] 215 | 优先级: 216 | * 传入的 tableName 和 schema 217 | * 实体标记的 TableAttribute 218 | * 实体名称, schema 不设置 219 | 220 | 221 | 222 | 223 | 224 | 225 | 226 | 227 | 转换视图名称 228 | 229 | 230 | 231 | 232 | 233 | 234 | 设置所有列名,部分特殊列需要手动处理 235 | [Set all column names. Some special columns need to be handled manually] 236 | 237 | 238 | 239 | 240 | 241 | 242 | 设置列名 [Set the column name] 243 | 优先级: 244 | * 字段标记的 ColumnAttribute 的 Name 245 | * 传入的 columnName 246 | * fieldName 247 | 248 | 249 | 250 | 251 | 252 | 253 | 254 | 设置列名(自动转换为大小写) 255 | 256 | 257 | 258 | ModelBuiler 259 | 属性表达式 260 | 指定列名(不填则使用属性名称) 261 | 262 | 263 | 264 | 265 | 设置列名(自动转换为大小写) 266 | 267 | 268 | ModelBuiler 269 | 字段(属性名称) 270 | 指定列名(不填则使用属性名称) 271 | Property Builder 272 | 273 | 274 | 275 | 检查属性是否为可映射到数据库 276 | [Check if the property is mappable to the database] 277 | 278 | 279 | 是返回true,否返回false 280 | 281 | 282 | 283 | 检查属性是否是字符串类型,且没有设置长度 284 | [Checks whether the property is of type string and does not set the length] 285 | 286 | 287 | 288 | 289 | 290 | 291 | 检查是否是静态成员 292 | [Check if it is a static member] 293 | 294 | 295 | 296 | 297 | 298 | 检查是否为枚举 299 | [Check if it is an enumeration] 300 | 301 | 302 | 303 | 304 | 305 | 306 | 获取 TableAttribute 307 | [Get TableAttribute] 308 | 309 | 310 | 311 | 312 | 313 | 314 | 获取 ColumnAttribute 315 | [Get ColumnAttribute] 316 | 317 | 318 | 319 | 320 | 321 | 322 | 获取 ColumnAttribute 323 | [Get ColumnAttribute] 324 | 325 | 326 | 327 | 328 | 329 | 330 | 获取 DbSet 或 DbQuery 类型字符串 331 | [Gets the DbSet type string] 332 | 333 | 334 | 335 | 336 | 337 | 338 | 获取 DbSet 或 DbQuery 类型字符串 339 | [Get the DbSet or DbQuery type string] 340 | 341 | 342 | 343 | 344 | 345 | 346 | 获取 DbSet 或 DbQuery 类型 347 | [Get the DbSet or DbQuery type] 348 | 349 | 350 | 351 | 352 | 353 | 354 | 根据配置的转换类型转换大小写 355 | 356 | 357 | 358 | 359 | 360 | 361 | 设置转换类型 362 | 363 | 364 | 365 | 366 | 367 | 368 | 设置转换类型 369 | 370 | 371 | 372 | 373 | 374 | 转换字符串大小写 375 | [Converts string case] 376 | 377 | 378 | 379 | 380 | 381 | 382 | 383 | 忽略已存在的 EntityTypeConfiguration 校验函数 384 | [The existing EntityTypeConfiguration validation function is ignored] 385 | 386 | 387 | 388 | 389 | 390 | 391 | 392 | -------------------------------------------------------------------------------- /src/E.EntityFrameworkCore.Extensions/EntityFrameworkCoreTableViewExtensions.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Linq; 3 | using System.Reflection; 4 | using System.Collections.Generic; 5 | using System.Text.RegularExpressions; 6 | using System.ComponentModel.DataAnnotations; 7 | using System.ComponentModel.DataAnnotations.Schema; 8 | using Microsoft.EntityFrameworkCore; 9 | using Microsoft.EntityFrameworkCore.Metadata.Builders; 10 | using System.Linq.Expressions; 11 | 12 | namespace E 13 | { 14 | /// 15 | /// EntityFrameworkCore 表和视图的扩展 16 | /// [Extension to the EntityFrameworkCore table and view] 17 | /// 18 | public static class EntityFrameworkCoreTableViewExtensions 19 | { 20 | #region 可自定义配置 [Customizable configuration] 21 | 22 | /// 23 | /// 列名大小写转换类型,默认为不转换 24 | /// [Enables uppercase, false by default, and lowercase by default] 25 | /// 26 | public static ColumnNameCaseType CaseType { get; private set; } = ColumnNameCaseType.Default; 27 | /// 28 | /// 启用设置字符串默认长度,默认为 false 29 | /// [Sets the default length of the string to false by default] 30 | /// 31 | public static bool UseDefaultStringMaxLength { get; set; } 32 | /// 33 | /// 默认字符串使用的长度 (默认 512) 34 | /// [The length of the default string used (default 512)] 35 | /// 36 | public static int DefaultStringMaxLength { get; set; } = 512; 37 | /// 38 | /// 外部自定义属性映射到字段检查方法 39 | /// [External custom attributes map to field inspection methods] 40 | /// 41 | public static Func ColumnCheck { get; set; } 42 | /// 43 | /// 所有允许映射到数据库的字段类型(谨慎更改) 44 | /// [All field types that allow mapping to the database (changed carefully)] 45 | /// 46 | public static List DbMapTypes { get; set; } = new List() { 47 | "System.Boolean", 48 | "System.Byte", 49 | "System.Byte[]", 50 | "System.SByte", 51 | "System.Char", 52 | "System.Decimal", 53 | "System.Double", 54 | "System.Single", 55 | "System.Int32", 56 | "System.UInt32", 57 | "System.Int64", 58 | "System.UInt64", 59 | "System.Int16", 60 | "System.UInt16", 61 | "System.String", 62 | "System.DateTime", 63 | "System.Guid", 64 | }; 65 | /// 66 | /// DbSet 类型字符串(谨慎修改) 67 | /// [DbSet type string (carefully modified)] 68 | /// 69 | public static string DbSetTypeStr { get; set; } = "Microsoft.EntityFrameworkCore.DbSet"; 70 | 71 | /// 72 | /// 外部自定义 DbSet 是否处理的检查方法 73 | /// [External custom DbSet whether to handle the check method] 74 | /// 75 | public static Func DbSetCheck { get; set; } 76 | /// 77 | /// 启用列名最大长度限制,默认为fasle 78 | /// [Enables the maximum length limit for column names, which is fasle by default] 79 | /// 80 | public static bool UseColumnNameMaxLength { get; set; } 81 | /// 82 | /// 列名最大长度,默认30 83 | /// [Column name maximum length, default 30] 84 | /// 85 | public static int ColumnNameMaxLength { get; set; } = 30; 86 | /// 87 | /// IEntityTypeConfiguration 接口字符串 88 | /// 89 | public static string IEntityTypeConfigurationTypeStr { get; set; } = typeof(IEntityTypeConfiguration<>).FullName; 90 | 91 | /// 92 | /// 使用DbSet名称为数据库表名称 93 | /// 94 | public static bool UseDbSetNameToTableName { get; set; } = true; 95 | 96 | /// 97 | /// 外部自定义 设置字符串类型列数据长度 是否处理的检查方法 98 | /// 99 | public static Func CheckUseDefaultStringMaxLength { get; set; } 100 | 101 | #endregion 102 | 103 | 104 | #region 内置配置(不可更改) [Built-in configuration (unchangeable)] 105 | 106 | /// 107 | /// 表特性类型 108 | /// [Table property type] 109 | /// 110 | static Type TableAttr { get; set; } = typeof(TableAttribute); 111 | /// 112 | /// 列特性类型 113 | /// [Column attribute type] 114 | /// 115 | static Type ColumnAttr { get; set; } = typeof(ColumnAttribute); 116 | /// 117 | /// 不映射特性类型 118 | /// [Attribute types are not mapped] 119 | /// 120 | static Type NoMappedAttribute { get; set; } = typeof(NotMappedAttribute); 121 | /// 122 | /// 字符串类型 123 | /// [String type] 124 | /// 125 | static Type StringType { get; set; } = typeof(string); 126 | 127 | /// 128 | /// 字符串长度特性类型 129 | /// [String length attribute type] 130 | /// 131 | static Type StringLengthAttr { get; set; } = typeof(StringLengthAttribute); 132 | 133 | /// 134 | /// 实现 IEntityTypeConfiguration 类型的集合 135 | /// 136 | static List EntityCfgTypes { get; set; } 137 | 138 | #endregion 139 | 140 | 141 | #region 公开 数据库上下文扩展函数 ModelBuilder(DbContext) 142 | 143 | 144 | /// 145 | /// 设置DbContext的所有DbSet 对应的 表名和列名 146 | /// [Set the table and column names for all dbsets of the DbContext] 147 | /// 148 | /// 149 | /// 150 | /// 自动跳过处理 DbContext 程序集中已实现的 IEntityTypeConfiguration的DbSet 151 | /// 152 | public static ModelBuilder CaseAllDbSetNameAndColumnName(this ModelBuilder builder, 153 | bool ignoreExistEntityTypeConfigurations = false) 154 | where TDbContext : DbContext 155 | { 156 | var properties = typeof(TDbContext).GetProperties(); 157 | 158 | var allDbSet = properties.Where(o => o.PropertyType.FullName.StartsWith(DbSetTypeStr)).ToList(); 159 | 160 | if (allDbSet == null || allDbSet.Count == 0) 161 | { 162 | return builder; 163 | } 164 | 165 | var dbSetName = string.Empty; 166 | var dbSetTypeStr = string.Empty; 167 | 168 | 169 | 170 | foreach (var dbSet in allDbSet) 171 | { 172 | if (ignoreExistEntityTypeConfigurations && dbSet.IgnoreExistEntityTypeConfigurations()) 173 | { 174 | continue; 175 | } 176 | 177 | if (DbSetCheck != null && !DbSetCheck(dbSet)) 178 | { 179 | continue; 180 | } 181 | 182 | dbSetName = dbSet.Name; 183 | dbSetTypeStr = dbSet.GetDbSetOrDbQueryTypeStr(); 184 | 185 | builder.Entity(dbSetTypeStr, (entityTypeBuilder) => 186 | { 187 | entityTypeBuilder.CaseTableNameAndAllCloumName( 188 | UseDbSetNameToTableName ? dbSetName : null 189 | ); 190 | }); 191 | } 192 | 193 | return builder; 194 | } 195 | 196 | #endregion 197 | 198 | 199 | #region 公开 表扩展函数 EntityTypeBuilder [Public table extension function EntityTypeBuilder] 200 | 201 | /// 202 | /// 自动将表名和列名转换大小写,部分特殊列需要手动处理 203 | /// [Automatically converts table and column names to case, and some special columns need to be handled manually] 204 | /// 205 | /// 206 | /// 207 | /// 208 | /// 209 | public static EntityTypeBuilder CaseTableNameAndAllCloumName( 210 | this EntityTypeBuilder builder, string tableName = null, string schema = null) 211 | { 212 | builder.CaseTableName(tableName, schema); 213 | 214 | return builder.CaseAllColumnName(); 215 | } 216 | 217 | 218 | /// 219 | /// 设置表名和Schema [Set the table name and Schema] 220 | /// 优先级: 221 | /// * 传入的 tableName 和 schema 222 | /// * 实体标记的 TableAttribute 223 | /// * 实体名称, schema 不设置 224 | /// 225 | /// 226 | /// 227 | /// 228 | /// 229 | public static EntityTypeBuilder CaseTableName( 230 | this EntityTypeBuilder builder, 231 | string tableName = null, 232 | string schema = null) 233 | { 234 | if (builder.Metadata.BaseType != null) 235 | { 236 | return builder; 237 | } 238 | 239 | if (!string.IsNullOrWhiteSpace(tableName)) 240 | { 241 | //return RelationalEntityTypeBuilderExtensions.ToTable(builder, C(tableName), C(schema)); 242 | return builder.ToTable(C(tableName), C(schema)); 243 | } 244 | 245 | var tableAttr = builder.Metadata.ClrType.GetTableAttribute(); 246 | if (tableAttr != null) 247 | { 248 | //return RelationalEntityTypeBuilderExtensions.ToTable(builder, C(tableAttr.Name), C(tableAttr.Schema)); 249 | return builder.ToTable(C(tableAttr.Name), C(tableAttr.Schema)); 250 | } 251 | //return RelationalEntityTypeBuilderExtensions.ToTable(builder, C(builder.Metadata.ClrType.Name)); 252 | return builder.ToTable(C(builder.Metadata.ClrType.Name)); 253 | } 254 | 255 | #endregion 256 | 257 | 258 | #region 公开 公共 设置列名函数 259 | 260 | 261 | /// 262 | /// 设置所有列名,部分特殊列需要手动处理 263 | /// [Set all column names. Some special columns need to be handled manually] 264 | /// 265 | /// 266 | /// 267 | public static EntityTypeBuilder CaseAllColumnName(this EntityTypeBuilder builder) 268 | { 269 | var entityProps = builder.Metadata.ClrType.GetProperties(); 270 | 271 | // 字段 272 | var cloumnName = string.Empty; 273 | 274 | foreach (var prop in entityProps) 275 | { 276 | if (!prop.CheckPropIsColumn()) 277 | { 278 | continue; 279 | } 280 | 281 | // 设置字段列名 282 | var propertyBuilder = builder.Property(prop.PropertyType, prop.Name); 283 | propertyBuilder.CaseColumnName(prop.Name); 284 | 285 | 286 | // 设置string类型列数据长度 287 | if (UseDefaultStringMaxLength && prop.CheckPropIsStringAndNoSetMaxLength()) 288 | { 289 | // 如果自定义了检查函数,那么优先判断检查函数 290 | if (CheckUseDefaultStringMaxLength != null) 291 | { 292 | var checkResult = CheckUseDefaultStringMaxLength(builder.Metadata.ClrType, prop); 293 | // 不通过检查,跳过设置默认数据长度 294 | if (!checkResult.Success) 295 | { 296 | continue; 297 | } 298 | 299 | // 额外配置的长度 300 | if (checkResult.MaxLength.HasValue && checkResult.MaxLength.Value > 0) 301 | { 302 | // 设置字符串列默认长度 303 | propertyBuilder.HasMaxLength(checkResult.MaxLength.Value); 304 | continue; 305 | } 306 | } 307 | 308 | 309 | // 设置字符串列默认长度 310 | propertyBuilder.HasMaxLength(DefaultStringMaxLength); 311 | } 312 | } 313 | 314 | return builder; 315 | } 316 | 317 | 318 | /// 319 | /// 设置列名 [Set the column name] 320 | /// 优先级: 321 | /// * 字段标记的 ColumnAttribute 的 Name 322 | /// * 传入的 columnName 323 | /// * fieldName 324 | /// 325 | /// 326 | /// 327 | /// 328 | public static PropertyBuilder CaseColumnName( 329 | this PropertyBuilder property, 330 | string columnName = null 331 | ) 332 | { 333 | if (property.Metadata.PropertyInfo == null) 334 | { 335 | return property.HasColumnName(C(property.Metadata.Name, true)); 336 | } 337 | 338 | var columnAttr = property.Metadata.PropertyInfo.GetColumnAttribute(); 339 | if (columnAttr != null && !string.IsNullOrWhiteSpace(columnAttr.Name)) 340 | { 341 | return property.HasColumnName(C(columnAttr.Name, true)); 342 | } 343 | 344 | if (!string.IsNullOrWhiteSpace(columnName)) 345 | { 346 | return property.HasColumnName(C(columnName, true)); 347 | } 348 | 349 | var fieldName = Regex.Match(property.Metadata.FieldInfo.Name, "<(.*?)>").Groups[1].Value; 350 | return property.HasColumnName(C(fieldName, true)); 351 | } 352 | 353 | /// 354 | /// 设置列名(自动转换为大小写) 355 | /// 356 | /// 357 | /// 358 | /// ModelBuiler 359 | /// 属性表达式 360 | /// 指定列名(不填则使用属性名称) 361 | /// 362 | public static PropertyBuilder CaseColumnName( 363 | this EntityTypeBuilder builder, 364 | Expression> propertyExpression, 365 | string columnName = null) 366 | where TEntity : class 367 | { 368 | return ( 369 | builder.Property(propertyExpression).CaseColumnName(columnName) 370 | ) as PropertyBuilder; 371 | } 372 | 373 | /// 374 | /// 设置列名(自动转换为大小写) 375 | /// 376 | /// 377 | /// ModelBuiler 378 | /// 字段(属性名称) 379 | /// 指定列名(不填则使用属性名称) 380 | /// Property Builder 381 | public static PropertyBuilder CaseColumnName( 382 | this EntityTypeBuilder builder, 383 | string fieldName, 384 | string columnName = null) 385 | { 386 | return ( 387 | builder.Property(fieldName).CaseColumnName(columnName) 388 | ) as PropertyBuilder; 389 | } 390 | 391 | #endregion 392 | 393 | 394 | #region 公开 公共函数 395 | 396 | /// 397 | /// 检查属性是否为可映射到数据库 398 | /// [Check if the property is mappable to the database] 399 | /// 400 | /// 401 | /// 是返回true,否返回false 402 | public static bool CheckPropIsColumn(this PropertyInfo property) 403 | { 404 | // 是否不映射 405 | if (property.GetCustomAttribute(NoMappedAttribute, false) != null) 406 | { 407 | return false; 408 | } 409 | 410 | // 是否静态属性 411 | if (CheckStatic(property)) 412 | { 413 | return false; 414 | } 415 | 416 | // 检查枚举 417 | if (CheckEnum(property)) 418 | { 419 | return true; 420 | } 421 | 422 | // 如果自定义了检查器,并通过了检查,返回true 423 | if (ColumnCheck != null && ColumnCheck.Invoke(property)) 424 | { 425 | return true; 426 | } 427 | 428 | 429 | // 默认检查是否支持类型 430 | foreach (var item in DbMapTypes) 431 | { 432 | // 普通类型 433 | if (item == property.PropertyType.FullName) 434 | { 435 | return true; 436 | } 437 | 438 | // 可空 439 | if (property.PropertyType.FullName.StartsWith($"System.Nullable`1[[{item}, ")) 440 | { 441 | return true; 442 | } 443 | } 444 | 445 | return false; 446 | } 447 | 448 | /// 449 | /// 检查属性是否是字符串类型,且没有设置长度 450 | /// [Checks whether the property is of type string and does not set the length] 451 | /// 452 | /// 453 | /// 454 | public static bool CheckPropIsStringAndNoSetMaxLength(this PropertyInfo property) 455 | { 456 | return property.PropertyType == StringType 457 | && property.GetCustomAttribute(StringLengthAttr, false) == null; 458 | } 459 | 460 | /// 461 | /// 检查是否是静态成员 462 | /// [Check if it is a static member] 463 | /// 464 | /// 465 | public static bool CheckStatic(this PropertyInfo property) 466 | { 467 | var getMethod = property.GetMethod; 468 | if (getMethod != null) 469 | { 470 | return getMethod.IsStatic; 471 | } 472 | else 473 | { 474 | var setMethod = property.SetMethod; 475 | return setMethod.IsStatic; 476 | } 477 | } 478 | 479 | /// 480 | /// 检查是否为枚举 481 | /// [Check if it is an enumeration] 482 | /// 483 | /// 484 | /// 485 | public static bool CheckEnum(this PropertyInfo property) 486 | { 487 | // System.Enum 488 | if (property.PropertyType.BaseType != null && !string.IsNullOrWhiteSpace(property.PropertyType.BaseType.FullName)) 489 | { 490 | return property.PropertyType.BaseType.FullName == "System.Enum"; 491 | } 492 | 493 | return false; 494 | } 495 | 496 | /// 497 | /// 获取 TableAttribute 498 | /// [Get TableAttribute] 499 | /// 500 | /// 501 | /// 502 | public static TableAttribute GetTableAttribute(this Type type) 503 | { 504 | var tableAttr = type.GetCustomAttributes(TableAttr, false); 505 | if (tableAttr != null && tableAttr.Length >= 1) 506 | { 507 | var tableAttribute = (TableAttribute)tableAttr[0]; 508 | return tableAttribute; 509 | } 510 | 511 | return null; 512 | } 513 | 514 | /// 515 | /// 获取 ColumnAttribute 516 | /// [Get ColumnAttribute] 517 | /// 518 | /// 519 | /// 520 | public static ColumnAttribute GetColumnAttribute(this Type type) 521 | { 522 | var columnAttr = type.GetCustomAttributes(ColumnAttr, false); 523 | if (columnAttr != null && columnAttr.Length >= 1) 524 | { 525 | var columnAttribute = (ColumnAttribute)columnAttr[0]; 526 | return columnAttribute; 527 | } 528 | 529 | return null; 530 | } 531 | 532 | /// 533 | /// 获取 ColumnAttribute 534 | /// [Get ColumnAttribute] 535 | /// 536 | /// 537 | /// 538 | public static ColumnAttribute GetColumnAttribute(this PropertyInfo propertyInfo) 539 | { 540 | var columnAttr = propertyInfo.GetCustomAttributes(ColumnAttr, false); 541 | if (columnAttr != null && columnAttr.Length >= 1) 542 | { 543 | var columnAttribute = (ColumnAttribute)columnAttr[0]; 544 | return columnAttribute; 545 | } 546 | 547 | return null; 548 | } 549 | 550 | /// 551 | /// 获取 DbSet 或 DbQuery 类型字符串 552 | /// [Gets the DbSet type string] 553 | /// 554 | /// 555 | /// 556 | public static string GetDbSetOrDbQueryTypeStr(this Type type) 557 | { 558 | var startIndex = type.FullName.IndexOf("[[") + 2; 559 | var endIndex = type.FullName.IndexOf(","); 560 | var entityTypeStr = type.FullName.Substring(startIndex, endIndex - startIndex); 561 | 562 | return entityTypeStr; 563 | } 564 | 565 | 566 | /// 567 | /// 获取 DbSet 或 DbQuery 类型字符串 568 | /// [Get the DbSet or DbQuery type string] 569 | /// 570 | /// 571 | /// 572 | public static string GetDbSetOrDbQueryTypeStr(this PropertyInfo property) 573 | { 574 | var startIndex = property.PropertyType.FullName.IndexOf("[[") + 2; 575 | var endIndex = property.PropertyType.FullName.IndexOf(","); 576 | var entityTypeStr = property.PropertyType.FullName.Substring(startIndex, endIndex - startIndex); 577 | 578 | return entityTypeStr; 579 | } 580 | 581 | /// 582 | /// 获取 DbSet 或 DbQuery 类型 583 | /// [Get the DbSet or DbQuery type] 584 | /// 585 | /// 586 | /// 587 | public static Type GetDbSetOrDbQueryType(this PropertyInfo property) 588 | { 589 | var startIndex = property.PropertyType.FullName.IndexOf("[[") + 2; 590 | var endIndex = property.PropertyType.FullName.IndexOf("]]"); 591 | var entityTypeStr = property.PropertyType.FullName.Substring(startIndex, endIndex - startIndex); 592 | return Type.GetType(entityTypeStr); 593 | } 594 | 595 | /// 596 | /// 根据配置的转换类型转换大小写 597 | /// 598 | /// 599 | /// 600 | public static string C(string str) 601 | { 602 | switch (CaseType) 603 | { 604 | case ColumnNameCaseType.Upper: 605 | return str?.ToUpperInvariant(); 606 | case ColumnNameCaseType.Lower: 607 | return str?.ToLowerInvariant(); 608 | } 609 | 610 | return str; 611 | } 612 | 613 | #endregion 614 | 615 | #region 公开 设置转换类型 616 | 617 | /// 618 | /// 设置转换类型 619 | /// 620 | /// 621 | /// 622 | public static void SetCaseType(this ModelBuilder modelBuilder, ColumnNameCaseType caseType) 623 | { 624 | CaseType = caseType; 625 | } 626 | 627 | /// 628 | /// 设置转换类型 629 | /// 630 | /// 631 | public static void SetCaseType(ColumnNameCaseType caseType) 632 | { 633 | CaseType = caseType; 634 | } 635 | 636 | #endregion 637 | 638 | #region 私有函数 639 | 640 | /// 641 | /// 转换字符串大小写 642 | /// [Converts string case] 643 | /// 644 | /// 645 | /// 646 | /// 647 | private static string C(string str, bool isColum = false) 648 | { 649 | if (UseColumnNameMaxLength 650 | && isColum 651 | && !string.IsNullOrWhiteSpace(str) 652 | && str.Length > ColumnNameMaxLength) 653 | { 654 | str = str.Substring(0, ColumnNameMaxLength); 655 | } 656 | 657 | return C(str); 658 | } 659 | 660 | /// 661 | /// 忽略已存在的 EntityTypeConfiguration 校验函数 662 | /// [The existing EntityTypeConfiguration validation function is ignored] 663 | /// 664 | /// 665 | /// 666 | /// 667 | private static bool IgnoreExistEntityTypeConfigurations(this PropertyInfo property) 668 | where TDbContext : DbContext 669 | { 670 | if (EntityCfgTypes == null) 671 | { 672 | EntityCfgTypes = typeof(TDbContext).Assembly.GetTypes() 673 | .Where(t => 674 | { 675 | var implementedInterface = t.GetInterface(IEntityTypeConfigurationTypeStr); 676 | return implementedInterface != null; 677 | }) 678 | .ToList(); 679 | 680 | } 681 | 682 | return EntityCfgTypes.Exists(o => 683 | o.GetInterface(IEntityTypeConfigurationTypeStr).GetDbSetOrDbQueryTypeStr() == property.GetDbSetOrDbQueryTypeStr()); 684 | } 685 | 686 | #endregion 687 | } 688 | } 689 | -------------------------------------------------------------------------------- /test/TestWebApp/Controllers/HomeController.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Threading.Tasks; 5 | using Microsoft.AspNetCore.Mvc; 6 | using TestWebApp.Database; 7 | 8 | namespace TestWebApp.Controllers 9 | { 10 | public class HomeController : Controller 11 | { 12 | protected readonly BloggingContext _dbContext; 13 | 14 | public HomeController(BloggingContext dbContext) 15 | { 16 | _dbContext = dbContext; 17 | } 18 | 19 | // GET: // 20 | public IActionResult Index() 21 | { 22 | var res = _dbContext.Blogs.ToList(); 23 | 24 | return View(); 25 | } 26 | } 27 | } -------------------------------------------------------------------------------- /test/TestWebApp/Database/BloggingContext.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Threading.Tasks; 5 | using Microsoft.EntityFrameworkCore; 6 | using TestWebApp.Database.Models; 7 | using E; 8 | 9 | namespace TestWebApp.Database 10 | { 11 | public class BloggingContext : DbContext 12 | { 13 | public DbSet Blogs { get; set; } 14 | public DbSet Posts { get; set; } 15 | 16 | public DbSet TestView { get; set; } 17 | 18 | public BloggingContext(DbContextOptions options) 19 | : base(options) 20 | { 21 | } 22 | 23 | protected override void OnModelCreating(ModelBuilder modelBuilder) 24 | { 25 | base.OnModelCreating(modelBuilder); 26 | 27 | 28 | #region 自定义校验器 29 | 30 | // DbSet Check 31 | E.EntityFrameworkCoreTableViewExtensions.DbSetCheck = (info) => 32 | { 33 | // 你的校验逻辑 34 | return true;// or false 35 | }; 36 | // Column Chcek 37 | E.EntityFrameworkCoreTableViewExtensions.ColumnCheck = (info) => 38 | { 39 | // 你的校验逻辑 40 | return true;// or false 41 | }; 42 | 43 | #endregion 44 | 45 | 46 | // 配置... [configurations...] 47 | 48 | // 禁用 使用DbSet名称作为表名和视图名称,优先读Table标记,其次类名 49 | E.EntityFrameworkCoreTableViewExtensions.UseDbSetNameToTableName = false; 50 | 51 | 52 | #region 如果使用 postgre_sql [if use postgre_sql ] 53 | 54 | // 设置为全小写 55 | E.EntityFrameworkCoreTableViewExtensions.SetCaseType(modelBuilder, ColumnNameCaseType.Lower); 56 | 57 | 58 | // 添加映射字段类型 [Adds a string of mapped field types] 59 | 60 | E.EntityFrameworkCoreTableViewExtensions.DbMapTypes.Add("System.String[]"); 61 | E.EntityFrameworkCoreTableViewExtensions.DbMapTypes.Add("System.Boolean[]"); 62 | E.EntityFrameworkCoreTableViewExtensions.DbMapTypes.Add("System.Int32[]"); 63 | 64 | // 添加更多 [add more...] 65 | 66 | #endregion 67 | 68 | #region 如果使用 oracle [if use oracle] 69 | 70 | //// 设置大写 71 | //E.EntityFrameworkCoreTableViewExtensions.SetCaseType(modelBuilder, ColumnNameCaseType.Upper); 72 | 73 | //// 使用列名长度限制,最大30 74 | //E.EntityFrameworkCoreTableViewExtensions.UseColumnNameMaxLength = true; 75 | //E.EntityFrameworkCoreTableViewExtensions.ColumnNameMaxLength = 30; 76 | 77 | //// 使用默认字符串长度 78 | //E.EntityFrameworkCoreTableViewExtensions.UseDefaultStringMaxLength = true; 79 | //E.EntityFrameworkCoreTableViewExtensions.DefaultStringMaxLength = 256; 80 | //// 自定义 字符串列数据长度 是否设置默认长度 校验函数 81 | //E.EntityFrameworkCoreTableViewExtensions.CheckUseDefaultStringMaxLength = (type, prop) => 82 | //{ 83 | 84 | // var checkResult = new CheckUseDefaultStringMaxLenghtResult(); 85 | 86 | // // 如果实体的命名空间为 TestWebApp.Database.Models 则设置长度为200 87 | // if (type.Namespace.StartsWith("TestWebApp.Database.Models")) 88 | // { 89 | // checkResult.Success = true; 90 | // checkResult.MaxLength = 200; 91 | // } 92 | 93 | 94 | // return checkResult; 95 | //}; 96 | 97 | #endregion 98 | 99 | 100 | #region 如果使用postgresql 或者 oracle [if use postgre_sql or oracle] 101 | 102 | // 处理此数据库上下文类型中 DbSet 103 | modelBuilder.CaseAllDbSetNameAndColumnName(true); 104 | 105 | #endregion 106 | 107 | } 108 | 109 | 110 | } 111 | } 112 | -------------------------------------------------------------------------------- /test/TestWebApp/Database/Models/Model.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Threading.Tasks; 5 | 6 | namespace TestWebApp.Database.Models 7 | { 8 | public enum Test 9 | { 10 | A, 11 | B, 12 | C 13 | } 14 | 15 | public class Blog 16 | { 17 | public int Id { get; set; } 18 | 19 | public bool Bool { get; set; } 20 | //public bool[] Bools { get; set; } 21 | public byte Byte { get; set; } 22 | public byte[] Bytes { get; set; } 23 | public sbyte Sbyte { get; set; } 24 | //public sbyte[] Sbytes { get; set; } 25 | public char Char { get; set; } 26 | //public char[] Chars { get; set; } 27 | public decimal Decimal { get; set; } 28 | //public decimal[] Decimals { get; set; } 29 | public double Double { get; set; } 30 | //public double[] Doubles { get; set; } 31 | public float Float { get; set; } 32 | //public float[] Floats { get; set; } 33 | public int Int { get; set; } 34 | //public int[] Ints { get; set; } 35 | public uint UInt { get; set; } 36 | //public uint[] UInts { get; set; } 37 | public long Long { get; set; } 38 | //public long[] Longs { get; set; } 39 | public ulong ULong { get; set; } 40 | //public ulong[] ULongs { get; set; } 41 | //public object Object { get; set; } 42 | //public object[] Objects { get; set; } 43 | public short Short { get; set; } 44 | //public short[] Shorts { get; set; } 45 | public ushort UShort { get; set; } 46 | //public ushort[] UShorts { get; set; } 47 | public string String { get; set; } 48 | public string[] Strings { get; set; } 49 | 50 | public Test TestEnum { get; set; } 51 | 52 | } 53 | 54 | public class Post 55 | { 56 | public int Id { get; set; } 57 | public string Title { get; set; } 58 | public string Content { get; set; } 59 | public int BlogId { get; set; } 60 | } 61 | 62 | 63 | public class TestView 64 | { 65 | public int Id { get; set; } 66 | 67 | public string Name { get; set; } 68 | 69 | public bool Enabled { get; set; } 70 | } 71 | 72 | } -------------------------------------------------------------------------------- /test/TestWebApp/Program.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.IO; 4 | using System.Linq; 5 | using System.Threading.Tasks; 6 | using Microsoft.AspNetCore; 7 | using Microsoft.AspNetCore.Hosting; 8 | using Microsoft.Extensions.Configuration; 9 | using Microsoft.Extensions.Logging; 10 | 11 | namespace TestWebApp 12 | { 13 | public class Program 14 | { 15 | public static void Main(string[] args) 16 | { 17 | CreateWebHostBuilder(args).Build().Run(); 18 | } 19 | 20 | public static IWebHostBuilder CreateWebHostBuilder(string[] args) => 21 | WebHost.CreateDefaultBuilder(args) 22 | .UseStartup(); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /test/TestWebApp/Startup.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Threading.Tasks; 5 | using Microsoft.AspNetCore.Builder; 6 | using Microsoft.AspNetCore.Hosting; 7 | using Microsoft.AspNetCore.Http; 8 | using Microsoft.AspNetCore.Mvc; 9 | using Microsoft.EntityFrameworkCore; 10 | using Microsoft.Extensions.DependencyInjection; 11 | using TestWebApp.Database; 12 | 13 | namespace TestWebApp 14 | { 15 | public class Startup 16 | { 17 | // This method gets called by the runtime. Use this method to add services to the container. 18 | // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940 19 | public void ConfigureServices(IServiceCollection services) 20 | { 21 | var connection = @"User ID=sa;Password=123;Host=127.0.0.1;Port=5432;Database=test_db;Pooling=true;"; 22 | 23 | services.AddDbContext 24 | (options => options.UseNpgsql(connection)); 25 | 26 | services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2); 27 | } 28 | 29 | // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. 30 | public void Configure(IApplicationBuilder app, IHostingEnvironment env) 31 | { 32 | if (env.IsDevelopment()) 33 | { 34 | app.UseDeveloperExceptionPage(); 35 | } 36 | 37 | app.UseMvcWithDefaultRoute(); 38 | } 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /test/TestWebApp/TestWebApp.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | netcoreapp3.1 5 | InProcess 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | -------------------------------------------------------------------------------- /test/TestWebApp/appsettings.Development.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Debug", 5 | "System": "Information", 6 | "Microsoft": "Information" 7 | } 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /test/TestWebApp/appsettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Warning" 5 | } 6 | }, 7 | "AllowedHosts": "*" 8 | } 9 | --------------------------------------------------------------------------------