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
{
/// <summary>
/// Creates an initial DbCommand object based on a stored procedure name
/// </summary>
/// <param name="context">target database context</param>
/// <param name="storedProcName">target procedure name</param>
/// <param name="prependDefaultSchema">Prepend the default schema name to <paramref name="storedProcName"/> if explicitly defined in <paramref name="context"/></param>
/// <param name="commandTimeout">Command timeout in seconds. Default is 30.</param>
/// <returns></returns>
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;
}
/// <summary>
/// Creates a DbParameter object and adds it to a DbCommand
/// </summary>
/// <param name="cmd"></param>
/// <param name="paramName"></param>
/// <param name="paramValue"></param>
/// <param name="configureParam"></param>
/// <returns></returns>
public static DbCommand WithSqlParam(this DbCommand cmd, string paramName, object paramValue,
Action<DbParameter> 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;
}
/// <summary>
/// Creates a DbParameter object and adds it to a DbCommand
/// </summary>
/// <param name="cmd"></param>
/// <param name="paramName"></param>
/// <param name="configureParam"></param>
/// <returns></returns>
public static DbCommand WithSqlParam(this DbCommand cmd, string paramName,
Action<DbParameter> 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;
}
/// <summary>
/// Adds a SqlParameter to a DbCommand.
/// This enabled the ability to provide custom types for SQL-parameters.
/// </summary>
/// <param name="cmd"></param>
/// <param name="parameter"></param>
/// <returns></returns>
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;
}
/// <summary>
/// Adds an array of SqlParameters to a DbCommand
/// </summary>
/// <param name="cmd"></param>
/// <param name="parameters"></param>
/// <returns></returns>
/// <exception cref="InvalidOperationException"></exception>
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<T> ReadToList<T>() where T : new()
{
return MapToList<T>(_reader);
}
public T? ReadToValue<T>() where T : struct
{
return MapToValue<T>(_reader);
}
public Task<bool> NextResultAsync()
{
return _reader.NextResultAsync();
}
public Task<bool> NextResultAsync(CancellationToken ct)
{
return _reader.NextResultAsync(ct);
}
public bool NextResult()
{
return _reader.NextResult();
}
/// <summary>
/// Retrieves the column values from the stored procedure and maps them to <typeparamref name="T"/>'s properties
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="dr"></param>
/// <returns>IList<<typeparam name="T">></typeparam></returns>
private static IList<T> MapToList<T>(DbDataReader dr) where T : new()
{
var objList = new List<T>();
var props = typeof(T).GetRuntimeProperties().ToList();
var colMapping = dr.GetColumnSchema()
.Where(x => props.Any(y =>
string.Equals((y.GetCustomAttribute<ColumnAttribute>(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<ColumnAttribute>(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;
}
/// <summary>
/// Attempts to read the first value of the first row of the result set.
/// </summary>
private static T? MapToValue<T>(DbDataReader dr) where T : struct
{
if (!dr.HasRows)
return new T?();
if (dr.Read())
{
return dr.IsDBNull(0) ? new T?() : dr.GetFieldValue<T>(0);
}
return new T?();
}
}
/// <summary>
/// Executes a DbDataReader and passes the results to <paramref name="handleResults"/>
/// </summary>
/// <param name="command"></param>
/// <param name="handleResults"></param>
/// <param name="commandBehaviour"></param>
/// <param name="manageConnection"></param>
/// <returns></returns>
public static void ExecuteStoredProc(this DbCommand command, Action<SprocResults> 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();
}
}
}
}
/// <summary>
/// Executes a DbDataReader asynchronously and passes the results to <paramref name="handleResults"/>
/// </summary>
/// <param name="command"></param>
/// <param name="handleResults"></param>
/// <param name="commandBehaviour"></param>
/// <param name="ct"></param>
/// <param name="manageConnection"></param>
/// <returns></returns>
public static async Task ExecuteStoredProcAsync(this DbCommand command, Action<SprocResults> 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();
}
}
}
}
/// <summary>
/// Executes a DbDataReader asynchronously and passes the results thru all <paramref name="resultActions"/>
/// </summary>
/// <param name="command"></param>
/// <param name="commandBehaviour"></param>
/// <param name="ct"></param>
/// <param name="manageConnection"></param>
/// <param name="resultActions"></param>
/// <returns></returns>
public static async Task ExecuteStoredProcAsync(this DbCommand command,
CommandBehavior commandBehaviour = CommandBehavior.Default,
CancellationToken ct = default, bool manageConnection = true, params Action<SprocResults>[] 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();
}
}
}
}
/// <summary>
/// Executes a non-query.
/// </summary>
/// <param name="command"></param>
/// <param name="manageConnection"></param>
/// <returns></returns>
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;
}
/// <summary>
/// Executes a non-query asynchronously.
/// </summary>
/// <param name="command"></param>
/// <param name="ct"></param>
/// <param name="manageConnection"></param>
/// <returns></returns>
public static async Task<int> 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
================================================
<?xml version="1.0" encoding="utf-8"?>
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFrameworks>netstandard2.0;net5.0;net6.0</TargetFrameworks>
<GeneratePackageOnBuild>true</GeneratePackageOnBuild>
<AssemblyVersion>3.0.0.0</AssemblyVersion>
<FileVersion>3.0.0.0</FileVersion>
<PackageTags>snickler.efcore,entityframeworkcore,fluent,storedprocedure</PackageTags>
<PackageProjectUrl>https://github.com/snickler/EFCore-FluentStoredProcedure</PackageProjectUrl>
<PackageReadmeFile>README.md</PackageReadmeFile>
<Copyright>
</Copyright>
<PackageLicenseUrl>https://github.com/snickler/EFCore-FluentStoredProcedure/blob/master/LICENSE</PackageLicenseUrl>
<Authors>Jeremy Sinclair, contributors</Authors>
<Version>3.0.0</Version>
<Description>Fluent Stored Procedure Extensions for EntityFrameworkCore</Description>
<PackageId>Snickler.EFCore</PackageId>
<Product>Snickler.EFCore</Product>
</PropertyGroup>
<PropertyGroup>
<!-- Publish the repository URL in the built .nupkg (in the NuSpec <Repository> element) -->
<PublishRepositoryUrl>true</PublishRepositoryUrl>
<!-- Embed source files that are not tracked by the source control manager in the PDB -->
<EmbedUntrackedSources>true</EmbedUntrackedSources>
<!-- Recommended: Embed symbols containing Source Link in the main file (exe/dll) -->
<DebugType>embedded</DebugType>
</PropertyGroup>
<PropertyGroup Condition="'$(GITHUB_ACTIONS)' == 'true'">
<ContinuousIntegrationBuild>true</ContinuousIntegrationBuild>
</PropertyGroup>
<ItemGroup>
<None Include="..\..\..\README.md" Pack="true" PackagePath="\" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.0.0" PrivateAssets="All" />
</ItemGroup>
<ItemGroup Condition=" '$(TargetFramework)' == 'netstandard2.0'">
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="2.*" />
</ItemGroup>
<ItemGroup Condition=" '$(TargetFramework)' == 'net5.0'">
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="5.*" />
</ItemGroup>
<ItemGroup Condition=" '$(TargetFramework)' == 'net6.0'">
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="6.*" />
</ItemGroup>
</Project>
================================================
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<FooDto>();
// 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<FooDto>();
handler.NextResult();
var barResults = handler.ReadToList<BarDto>();
handler.NextResult();
var bazResults = handler.ReadToList<BazDto>()
});
```
### 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<FooDto>();
handler.NextResult();
var barResults = handler.ReadToList<BarDto>();
handler.NextResult();
var bazResults = handler.ReadToList<BazDto>()
});
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;
```
gitextract_visrdfet/ ├── .gitattributes ├── .github/ │ └── workflows/ │ └── dotnet.yml ├── .gitignore ├── EFCoreFluent/ │ ├── EFCoreFluent.sln │ └── src/ │ └── EFCoreFluent/ │ ├── EFExtensions.cs │ └── Snickler.EFCore.csproj ├── LICENSE └── README.md
SYMBOL INDEX (20 symbols across 1 files)
FILE: EFCoreFluent/src/EFCoreFluent/EFExtensions.cs
class EFExtensions (line 14) | public static class EFExtensions
method LoadStoredProc (line 24) | public static DbCommand LoadStoredProc(this DbContext context, string ...
method WithSqlParam (line 53) | public static DbCommand WithSqlParam(this DbCommand cmd, string paramN...
method WithSqlParam (line 74) | public static DbCommand WithSqlParam(this DbCommand cmd, string paramN...
method WithSqlParam (line 94) | public static DbCommand WithSqlParam(this DbCommand cmd, IDbDataParame...
method WithSqlParams (line 111) | public static DbCommand WithSqlParams(this DbCommand cmd, IDbDataParam...
class SprocResults (line 121) | public class SprocResults
method SprocResults (line 125) | public SprocResults(DbDataReader reader)
method ReadToList (line 130) | public IList<T> ReadToList<T>() where T : new()
method ReadToValue (line 135) | public T? ReadToValue<T>() where T : struct
method NextResultAsync (line 140) | public Task<bool> NextResultAsync()
method NextResultAsync (line 145) | public Task<bool> NextResultAsync(CancellationToken ct)
method NextResult (line 150) | public bool NextResult()
method MapToList (line 161) | private static IList<T> MapToList<T>(DbDataReader dr) where T : new()
method MapToValue (line 218) | private static T? MapToValue<T>(DbDataReader dr) where T : struct
method ExecuteStoredProc (line 240) | public static void ExecuteStoredProc(this DbCommand command, Action<Sp...
method ExecuteStoredProcAsync (line 280) | public static async Task ExecuteStoredProcAsync(this DbCommand command...
method ExecuteStoredProcAsync (line 321) | public static async Task ExecuteStoredProcAsync(this DbCommand command,
method ExecuteStoredNonQuery (line 361) | public static int ExecuteStoredNonQuery(this DbCommand command, bool m...
method ExecuteStoredNonQueryAsync (line 395) | public static async Task<int> ExecuteStoredNonQueryAsync(this DbComman...
Condensed preview — 8 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (34K chars).
[
{
"path": ".gitattributes",
"chars": 2518,
"preview": "###############################################################################\n# Set default behavior to automatically "
},
{
"path": ".github/workflows/dotnet.yml",
"chars": 572,
"preview": "name: .NET\n\non:\n push:\n branches: [ master ]\n\njobs:\n build:\n\n runs-on: ubuntu-latest\n\n steps:\n - uses: act"
},
{
"path": ".gitignore",
"chars": 4305,
"preview": "## Ignore Visual Studio temporary files, build results, and\n## files generated by popular Visual Studio add-ons.\n\n# User"
},
{
"path": "EFCoreFluent/EFCoreFluent.sln",
"chars": 1115,
"preview": "\nMicrosoft Visual Studio Solution File, Format Version 12.00\n# Visual Studio 15\nVisualStudioVersion = 15.0.26403.7\nMini"
},
{
"path": "EFCoreFluent/src/EFCoreFluent/EFExtensions.cs",
"chars": 15716,
"preview": "using Microsoft.EntityFrameworkCore;\nusing System;\nusing System.Collections.Generic;\nusing System.ComponentModel.DataAn"
},
{
"path": "EFCoreFluent/src/EFCoreFluent/Snickler.EFCore.csproj",
"chars": 2258,
"preview": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<Project Sdk=\"Microsoft.NET.Sdk\">\n\t<PropertyGroup>\n\t\t<TargetFrameworks>netstanda"
},
{
"path": "LICENSE",
"chars": 1072,
"preview": "MIT License\n\nCopyright (c) 2017 Jeremy Sinclair\n\nPermission is hereby granted, free of charge, to any person obtaining a"
},
{
"path": "README.md",
"chars": 4456,
"preview": "# Snickler.EFCore\nFluent Methods for mapping Stored Procedure results to objects in EntityFrameworkCore\n\n\n\n[. The extraction includes 8 files (31.3 KB), approximately 7.1k tokens, and a symbol index with 20 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.
Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.