Repository: snickler/EFCore-FluentStoredProcedure
Branch: main
Commit: 8f47796d2ad0
Files: 8
Total size: 31.3 KB
Directory structure:
gitextract_visrdfet/
├── .gitattributes
├── .github/
│ └── workflows/
│ └── dotnet.yml
├── .gitignore
├── EFCoreFluent/
│ ├── EFCoreFluent.sln
│ └── src/
│ └── EFCoreFluent/
│ ├── EFExtensions.cs
│ └── Snickler.EFCore.csproj
├── LICENSE
└── README.md
================================================
FILE CONTENTS
================================================
================================================
FILE: .gitattributes
================================================
###############################################################################
# Set default behavior to automatically normalize line endings.
###############################################################################
* text=auto
###############################################################################
# Set default behavior for command prompt diff.
#
# This is need for earlier builds of msysgit that does not have it on by
# default for csharp files.
# Note: This is only used by command line
###############################################################################
#*.cs diff=csharp
###############################################################################
# Set the merge driver for project and solution files
#
# Merging from the command prompt will add diff markers to the files if there
# are conflicts (Merging from VS is not affected by the settings below, in VS
# the diff markers are never inserted). Diff markers may cause the following
# file extensions to fail to load in VS. An alternative would be to treat
# these files as binary and thus will always conflict and require user
# intervention with every merge. To do so, just uncomment the entries below
###############################################################################
#*.sln merge=binary
#*.csproj merge=binary
#*.vbproj merge=binary
#*.vcxproj merge=binary
#*.vcproj merge=binary
#*.dbproj merge=binary
#*.fsproj merge=binary
#*.lsproj merge=binary
#*.wixproj merge=binary
#*.modelproj merge=binary
#*.sqlproj merge=binary
#*.wwaproj merge=binary
###############################################################################
# behavior for image files
#
# image files are treated as binary by default.
###############################################################################
#*.jpg binary
#*.png binary
#*.gif binary
###############################################################################
# diff behavior for common document formats
#
# Convert binary document formats to text before diffing them. This feature
# is only available from the command line. Turn it on by uncommenting the
# entries below.
###############################################################################
#*.doc diff=astextplain
#*.DOC diff=astextplain
#*.docx diff=astextplain
#*.DOCX diff=astextplain
#*.dot diff=astextplain
#*.DOT diff=astextplain
#*.pdf diff=astextplain
#*.PDF diff=astextplain
#*.rtf diff=astextplain
#*.RTF diff=astextplain
================================================
FILE: .github/workflows/dotnet.yml
================================================
name: .NET
on:
push:
branches: [ master ]
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Setup .NET
uses: actions/setup-dotnet@v1
with:
dotnet-version: 6.0.x
- name: Restore dependencies
run: dotnet restore EFCoreFluent
- name: Build
run: dotnet build EFCoreFluent --no-restore -c Release
- name: Publish Artifact
uses: actions/upload-artifact@v2.3.0
with:
name: Package
path: "EFCoreFluent/src/EFCoreFluent/bin/Release/**.nupkg"
================================================
FILE: .gitignore
================================================
## Ignore Visual Studio temporary files, build results, and
## files generated by popular Visual Studio add-ons.
# User-specific files
*.suo
*.user
*.userosscache
*.sln.docstates
# User-specific files (MonoDevelop/Xamarin Studio)
*.userprefs
# Build results
[Dd]ebug/
[Dd]ebugPublic/
[Rr]elease/
[Rr]eleases/
x64/
x86/
bld/
[Bb]in/
[Oo]bj/
[Ll]og/
# Visual Studio 2015 cache/options directory
.vs/
# Uncomment if you have tasks that create the project's static files in wwwroot
#wwwroot/
# MSTest test Results
[Tt]est[Rr]esult*/
[Bb]uild[Ll]og.*
# NUNIT
*.VisualState.xml
TestResult.xml
# Build Results of an ATL Project
[Dd]ebugPS/
[Rr]eleasePS/
dlldata.c
# DNX
project.lock.json
project.fragment.lock.json
artifacts/
*_i.c
*_p.c
*_i.h
*.ilk
*.meta
*.obj
*.pch
*.pdb
*.pgc
*.pgd
*.rsp
*.sbr
*.tlb
*.tli
*.tlh
*.tmp
*.tmp_proj
*.log
*.vspscc
*.vssscc
.builds
*.pidb
*.svclog
*.scc
# Chutzpah Test files
_Chutzpah*
# Visual C++ cache files
ipch/
*.aps
*.ncb
*.opendb
*.opensdf
*.sdf
*.cachefile
*.VC.db
*.VC.VC.opendb
# Visual Studio profiler
*.psess
*.vsp
*.vspx
*.sap
# TFS 2012 Local Workspace
$tf/
# Guidance Automation Toolkit
*.gpState
# ReSharper is a .NET coding add-in
_ReSharper*/
*.[Rr]e[Ss]harper
*.DotSettings.user
# JustCode is a .NET coding add-in
.JustCode
# TeamCity is a build add-in
_TeamCity*
# DotCover is a Code Coverage Tool
*.dotCover
# NCrunch
_NCrunch_*
.*crunch*.local.xml
nCrunchTemp_*
# MightyMoose
*.mm.*
AutoTest.Net/
# Web workbench (sass)
.sass-cache/
# Installshield output folder
[Ee]xpress/
# DocProject is a documentation generator add-in
DocProject/buildhelp/
DocProject/Help/*.HxT
DocProject/Help/*.HxC
DocProject/Help/*.hhc
DocProject/Help/*.hhk
DocProject/Help/*.hhp
DocProject/Help/Html2
DocProject/Help/html
# Click-Once directory
publish/
# Publish Web Output
*.[Pp]ublish.xml
*.azurePubxml
# TODO: Comment the next line if you want to checkin your web deploy settings
# but database connection strings (with potential passwords) will be unencrypted
#*.pubxml
*.publishproj
# Microsoft Azure Web App publish settings. Comment the next line if you want to
# checkin your Azure Web App publish settings, but sensitive information contained
# in these scripts will be unencrypted
PublishScripts/
# NuGet Packages
*.nupkg
# The packages folder can be ignored because of Package Restore
**/packages/*
# except build/, which is used as an MSBuild target.
!**/packages/build/
# Uncomment if necessary however generally it will be regenerated when needed
#!**/packages/repositories.config
# NuGet v3's project.json files produces more ignoreable files
*.nuget.props
*.nuget.targets
# Microsoft Azure Build Output
csx/
*.build.csdef
# Microsoft Azure Emulator
ecf/
rcf/
# Windows Store app package directories and files
AppPackages/
BundleArtifacts/
Package.StoreAssociation.xml
_pkginfo.txt
# Visual Studio cache files
# files ending in .cache can be ignored
*.[Cc]ache
# but keep track of directories ending in .cache
!*.[Cc]ache/
# Others
ClientBin/
~$*
*~
*.dbmdl
*.dbproj.schemaview
*.jfm
*.pfx
*.publishsettings
node_modules/
orleans.codegen.cs
# Since there are multiple workflows, uncomment next line to ignore bower_components
# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
#bower_components/
# RIA/Silverlight projects
Generated_Code/
# Backup & report files from converting an old project file
# to a newer Visual Studio version. Backup files are not needed,
# because we have git ;-)
_UpgradeReport_Files/
Backup*/
UpgradeLog*.XML
UpgradeLog*.htm
# SQL Server files
*.mdf
*.ldf
# Business Intelligence projects
*.rdl.data
*.bim.layout
*.bim_*.settings
# Microsoft Fakes
FakesAssemblies/
# GhostDoc plugin setting file
*.GhostDoc.xml
# Node.js Tools for Visual Studio
.ntvs_analysis.dat
# Visual Studio 6 build log
*.plg
# Visual Studio 6 workspace options file
*.opt
# Visual Studio LightSwitch build output
**/*.HTMLClient/GeneratedArtifacts
**/*.DesktopClient/GeneratedArtifacts
**/*.DesktopClient/ModelManifest.xml
**/*.Server/GeneratedArtifacts
**/*.Server/ModelManifest.xml
_Pvt_Extensions
# Paket dependency manager
.paket/paket.exe
paket-files/
# FAKE - F# Make
.fake/
# JetBrains Rider
.idea/
*.sln.iml
# CodeRush
.cr/
# Python Tools for Visual Studio (PTVS)
__pycache__/
*.pyc
================================================
FILE: EFCoreFluent/EFCoreFluent.sln
================================================
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 15
VisualStudioVersion = 15.0.26403.7
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Snickler.EFCore", "src\EFCoreFluent\Snickler.EFCore.csproj", "{176191B5-C07B-4476-A213-416F122274BB}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{176191B5-C07B-4476-A213-416F122274BB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{176191B5-C07B-4476-A213-416F122274BB}.Debug|Any CPU.Build.0 = Debug|Any CPU
{176191B5-C07B-4476-A213-416F122274BB}.Release|Any CPU.ActiveCfg = Release|Any CPU
{176191B5-C07B-4476-A213-416F122274BB}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {D4190F00-F00E-4E37-8A65-A0B42B135CCA}
EndGlobalSection
EndGlobal
================================================
FILE: EFCoreFluent/src/EFCoreFluent/EFExtensions.cs
================================================
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data;
using System.Data.Common;
using System.Linq;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
namespace Snickler.EFCore
{
public static class EFExtensions
{
///
/// Creates an initial DbCommand object based on a stored procedure name
///
/// target database context
/// target procedure name
/// Prepend the default schema name to if explicitly defined in
/// Command timeout in seconds. Default is 30.
///
public static DbCommand LoadStoredProc(this DbContext context, string storedProcName,
bool prependDefaultSchema = true, short commandTimeout = 30)
{
var cmd = context.Database.GetDbConnection().CreateCommand();
cmd.CommandTimeout = commandTimeout;
if (prependDefaultSchema)
{
var schemaName = context.Model["DefaultSchema"];
if (schemaName != null)
{
storedProcName = $"{schemaName}.{storedProcName}";
}
}
cmd.CommandText = storedProcName;
cmd.CommandType = CommandType.StoredProcedure;
return cmd;
}
///
/// Creates a DbParameter object and adds it to a DbCommand
///
///
///
///
///
///
public static DbCommand WithSqlParam(this DbCommand cmd, string paramName, object paramValue,
Action configureParam = null)
{
if (string.IsNullOrEmpty(cmd.CommandText) && cmd.CommandType != System.Data.CommandType.StoredProcedure)
throw new InvalidOperationException("Call LoadStoredProc before using this method");
var param = cmd.CreateParameter();
param.ParameterName = paramName;
param.Value = paramValue ?? DBNull.Value;
configureParam?.Invoke(param);
cmd.Parameters.Add(param);
return cmd;
}
///
/// Creates a DbParameter object and adds it to a DbCommand
///
///
///
///
///
public static DbCommand WithSqlParam(this DbCommand cmd, string paramName,
Action configureParam = null)
{
if (string.IsNullOrEmpty(cmd.CommandText) && cmd.CommandType != CommandType.StoredProcedure)
throw new InvalidOperationException("Call LoadStoredProc before using this method");
var param = cmd.CreateParameter();
param.ParameterName = paramName;
configureParam?.Invoke(param);
cmd.Parameters.Add(param);
return cmd;
}
///
/// Adds a SqlParameter to a DbCommand.
/// This enabled the ability to provide custom types for SQL-parameters.
///
///
///
///
public static DbCommand WithSqlParam(this DbCommand cmd, IDbDataParameter parameter)
{
if (string.IsNullOrEmpty(cmd.CommandText) && cmd.CommandType != System.Data.CommandType.StoredProcedure)
throw new InvalidOperationException("Call LoadStoredProc before using this method");
cmd.Parameters.Add(parameter);
return cmd;
}
///
/// Adds an array of SqlParameters to a DbCommand
///
///
///
///
///
public static DbCommand WithSqlParams(this DbCommand cmd, IDbDataParameter[] parameters)
{
if (string.IsNullOrEmpty(cmd.CommandText) && cmd.CommandType != System.Data.CommandType.StoredProcedure)
throw new InvalidOperationException("Call LoadStoredProc before using this method");
cmd.Parameters.AddRange(parameters);
return cmd;
}
public class SprocResults
{
private readonly DbDataReader _reader;
public SprocResults(DbDataReader reader)
{
_reader = reader;
}
public IList ReadToList() where T : new()
{
return MapToList(_reader);
}
public T? ReadToValue() where T : struct
{
return MapToValue(_reader);
}
public Task NextResultAsync()
{
return _reader.NextResultAsync();
}
public Task NextResultAsync(CancellationToken ct)
{
return _reader.NextResultAsync(ct);
}
public bool NextResult()
{
return _reader.NextResult();
}
///
/// Retrieves the column values from the stored procedure and maps them to 's properties
///
///
///
/// IList<>
private static IList MapToList(DbDataReader dr) where T : new()
{
var objList = new List();
var props = typeof(T).GetRuntimeProperties().ToList();
var colMapping = dr.GetColumnSchema()
.Where(x => props.Any(y =>
string.Equals((y.GetCustomAttribute(true)?.Name ?? y.Name), x.ColumnName, StringComparison.CurrentCultureIgnoreCase)))
.ToDictionary(key => key.ColumnName.ToUpper());
if (!dr.HasRows)
return objList;
while (dr.Read())
{
var obj = new T();
foreach (var prop in props)
{
var upperName = (prop.GetCustomAttribute(true)?.Name ?? prop.Name).ToUpper();
if (!colMapping.ContainsKey(upperName))
continue;
var column = colMapping[upperName];
if (column?.ColumnOrdinal == null)
continue;
var val = dr.GetValue(column.ColumnOrdinal.Value);
// Handle DateOnly and TimeOnly conversions, not supported by DBDataReader
if (columnValue is DateTime dateTime)
{
Type propertyType = Nullable.GetUnderlyingType(property.PropertyType) ?? property.PropertyType;
if (propertyType == typeof(DateOnly))
{
columnValue = DateOnly.FromDateTime(dateTime);
}
else if (propertyType == typeof(TimeOnly))
{
columnValue = TimeOnly.FromDateTime(dateTime);
}
}
prop.SetValue(obj, val == DBNull.Value ? null : val);
}
objList.Add(obj);
}
return objList;
}
///
/// Attempts to read the first value of the first row of the result set.
///
private static T? MapToValue(DbDataReader dr) where T : struct
{
if (!dr.HasRows)
return new T?();
if (dr.Read())
{
return dr.IsDBNull(0) ? new T?() : dr.GetFieldValue(0);
}
return new T?();
}
}
///
/// Executes a DbDataReader and passes the results to
///
///
///
///
///
///
public static void ExecuteStoredProc(this DbCommand command, Action handleResults,
CommandBehavior commandBehaviour = CommandBehavior.Default,
bool manageConnection = true)
{
if (handleResults == null)
{
throw new ArgumentNullException(nameof(handleResults));
}
using (command)
{
if (manageConnection && command.Connection.State == ConnectionState.Closed)
command.Connection.Open();
try
{
using (var reader = command.ExecuteReader(commandBehaviour))
{
var sprocResults = new SprocResults(reader);
handleResults(sprocResults);
}
}
finally
{
if (manageConnection)
{
command.Connection.Close();
}
}
}
}
///
/// Executes a DbDataReader asynchronously and passes the results to
///
///
///
///
///
///
///
public static async Task ExecuteStoredProcAsync(this DbCommand command, Action handleResults,
System.Data.CommandBehavior commandBehaviour = System.Data.CommandBehavior.Default,
CancellationToken ct = default, bool manageConnection = true)
{
if (handleResults == null)
{
throw new ArgumentNullException(nameof(handleResults));
}
using (command)
{
if (manageConnection && command.Connection.State == System.Data.ConnectionState.Closed)
await command.Connection.OpenAsync(ct).ConfigureAwait(false);
try
{
using (var reader = await command.ExecuteReaderAsync(commandBehaviour, ct)
.ConfigureAwait(false))
{
var sprocResults = new SprocResults(reader);
handleResults(sprocResults);
}
}
finally
{
if (manageConnection)
{
command.Connection.Close();
}
}
}
}
///
/// Executes a DbDataReader asynchronously and passes the results thru all
///
///
///
///
///
///
///
public static async Task ExecuteStoredProcAsync(this DbCommand command,
CommandBehavior commandBehaviour = CommandBehavior.Default,
CancellationToken ct = default, bool manageConnection = true, params Action[] resultActions)
{
if (resultActions == null)
{
throw new ArgumentNullException(nameof(resultActions));
}
using (command)
{
if (manageConnection && command.Connection.State == ConnectionState.Closed)
await command.Connection.OpenAsync(ct).ConfigureAwait(false);
try
{
using (var reader = await command.ExecuteReaderAsync(commandBehaviour, ct)
.ConfigureAwait(false))
{
var sprocResults = new SprocResults(reader);
foreach (var t in resultActions)
t(sprocResults);
}
}
finally
{
if (manageConnection)
{
command.Connection.Close();
}
}
}
}
///
/// Executes a non-query.
///
///
///
///
public static int ExecuteStoredNonQuery(this DbCommand command, bool manageConnection = true)
{
var numberOfRecordsAffected = -1;
using (command)
{
if (command.Connection.State == ConnectionState.Closed)
{
command.Connection.Open();
}
try
{
numberOfRecordsAffected = command.ExecuteNonQuery();
}
finally
{
if (manageConnection)
{
command.Connection.Close();
}
}
}
return numberOfRecordsAffected;
}
///
/// Executes a non-query asynchronously.
///
///
///
///
///
public static async Task ExecuteStoredNonQueryAsync(this DbCommand command, CancellationToken ct = default,
bool manageConnection = true)
{
var numberOfRecordsAffected = -1;
using (command)
{
if (command.Connection.State == ConnectionState.Closed)
{
await command.Connection.OpenAsync(ct).ConfigureAwait(false);
}
try
{
numberOfRecordsAffected = await command.ExecuteNonQueryAsync(ct).ConfigureAwait(false);
}
finally
{
if (manageConnection)
{
command.Connection.Close();
}
}
}
return numberOfRecordsAffected;
}
}
}
================================================
FILE: EFCoreFluent/src/EFCoreFluent/Snickler.EFCore.csproj
================================================
netstandard2.0;net5.0;net6.0
true
3.0.0.0
3.0.0.0
snickler.efcore,entityframeworkcore,fluent,storedprocedure
https://github.com/snickler/EFCore-FluentStoredProcedure
README.md
https://github.com/snickler/EFCore-FluentStoredProcedure/blob/master/LICENSE
Jeremy Sinclair, contributors
3.0.0
Fluent Stored Procedure Extensions for EntityFrameworkCore
Snickler.EFCore
Snickler.EFCore
true
true
embedded
true
================================================
FILE: LICENSE
================================================
MIT License
Copyright (c) 2017 Jeremy Sinclair
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
================================================
FILE: README.md
================================================
# Snickler.EFCore
Fluent Methods for mapping Stored Procedure results to objects in EntityFrameworkCore
[](https://www.nuget.org/packages/Snickler.EFCore)
## Usage
### Executing A Stored Procedure
Add the `using` statement to pull in the extension method. E.g: `using Snickler.EFCore`
```csharp
var dbContext = GetDbContext();
dbContext.LoadStoredProc("dbo.SomeSproc")
.WithSqlParam("fooId", 1)
.ExecuteStoredProc((handler) =>
{
var fooResults = handler.ReadToList();
// do something with your results.
});
```
### Handling Multiple Result Sets
```csharp
var dbContext = GetDbContext();
dbContext.LoadStoredProc("dbo.SomeSproc")
.WithSqlParam("fooId", 1)
.ExecuteStoredProc((handler) =>
{
var fooResults = handler.ReadToList();
handler.NextResult();
var barResults = handler.ReadToList();
handler.NextResult();
var bazResults = handler.ReadToList()
});
```
### Handling Output Parameters
```csharp
DbParameter outputParam = null;
var dbContext = GetDbContext();
dbContext.LoadStoredProc("dbo.SomeSproc")
.WithSqlParam("fooId", 1)
.WithSqlParam("myOutputParam", (dbParam) =>
{
dbParam.Direction = System.Data.ParameterDirection.Output;
dbParam.DbType = System.Data.DbType.Int32;
outputParam = dbParam;
})
.ExecuteStoredProc((handler) =>
{
var fooResults = handler.ReadToList();
handler.NextResult();
var barResults = handler.ReadToList();
handler.NextResult();
var bazResults = handler.ReadToList()
});
int outputParamValue = (int)outputParam?.Value;
```
### Using output parameters without returning a result set
```csharp
DbParameter outputParam = null;
var dbContext = GetDbContext();
await dbContext.LoadStoredProc("dbo.SomeSproc")
.WithSqlParam("InputParam1", 1)
.WithSqlParam("myOutputParam", (dbParam) =>
{
dbParam.Direction = System.Data.ParameterDirection.Output;
dbParam.DbType = System.Data.DbType.Int16;
outputParam = dbParam;
})
.ExecuteStoredNonQueryAsync();
int outputParamValue = (short)outputParam.Value;
```
### Using output parameters without returning a result set but also getting the number of rows affected
Make sure your stored procedure does not contain `SET NOCOUNT ON`.
```csharp
int numberOfRowsAffected = -1;
DbParameter outputParam = null;
var dbContext = GetDbContext();
numberOfRowsAffected = await dbContext.LoadStoredProc("dbo.SomeSproc")
.WithSqlParam("InputParam1", 1)
.WithSqlParam("myOutputParam", (dbParam) =>
{
dbParam.Direction = System.Data.ParameterDirection.Output;
dbParam.DbType = System.Data.DbType.Int16;
outputParam = dbParam;
})
.ExecuteStoredNonQueryAsync();
int outputParamValue = (short)outputParam.Value;
```
### Changing the execution timeout when waiting for a stored procedure to return
```csharp
DbParameter outputParam = null;
var dbContext = GetDbContext();
// change timeout from 30 seconds to 300 seconds (5 minutes)
await dbContext.LoadStoredProc("dbo.SomeSproc", commandTimeout:300)
.WithSqlParam("InputParam1", 1)
.WithSqlParam("myOutputParam", (dbParam) =>
{
dbParam.Direction = System.Data.ParameterDirection.Output;
dbParam.DbType = System.Data.DbType.Int16;
outputParam = dbParam;
})
.ExecuteStoredNonQueryAsync();
int outputParamValue = (short)outputParam.Value;
```