FluentCommand.SqlServer 13.1.0

dotnet add package FluentCommand.SqlServer --version 13.1.0
                    
NuGet\Install-Package FluentCommand.SqlServer -Version 13.1.0
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="FluentCommand.SqlServer" Version="13.1.0" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="FluentCommand.SqlServer" Version="13.1.0" />
                    
Directory.Packages.props
<PackageReference Include="FluentCommand.SqlServer" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add FluentCommand.SqlServer --version 13.1.0
                    
#r "nuget: FluentCommand.SqlServer, 13.1.0"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#addin nuget:?package=FluentCommand.SqlServer&version=13.1.0
                    
Install FluentCommand.SqlServer as a Cake Addin
#tool nuget:?package=FluentCommand.SqlServer&version=13.1.0
                    
Install FluentCommand.SqlServer as a Cake Tool

FluentCommand

Fluent Wrapper for DbCommand.

Build status

Coverage Status

Package Version
FluentCommand FluentCommand
FluentCommand.SqlServer FluentCommand.SqlServer
FluentCommand.Json FluentCommand.Json

Download

The FluentCommand library is available on nuget.org via package name FluentCommand.

To install FluentCommand, run the following command in the Package Manager Console

PM> Install-Package FluentCommand

More information about NuGet package available at https://nuget.org/packages/FluentCommand

Features

  • Fluent wrapper over DbConnection and DbCommand
  • Callback for parameter return values
  • Automatic handling of connection state
  • Caching of results
  • Automatic creating of entity from DataReader via Dapper
  • Create Dynamic objects from DataReader via Dapper
  • Handles multiple result sets
  • Basic SQL query builder
  • Source Generate DataReader

Configuration

Configuration for SQL Server

IDataConfiguration dataConfiguration  = new DataConfiguration(
    SqlClientFactory.Instance, 
    ConnectionString
);

Register with dependency injection

services.AddFluentCommand(builder => builder
    .UseConnectionString(ConnectionString)
    .UseSqlServer()
);

Register using a connection name from the appsettings.json

services.AddFluentCommand(builder => builder
    .UseConnectionName("Tracker")
    .UseSqlServer()
);
{
  "ConnectionStrings": {
    "Tracker": "Data Source=(local);Initial Catalog=TrackerTest;Integrated Security=True;TrustServerCertificate=True;"
  }
}

Register for PostgreSQL

services.AddFluentCommand(builder => builder
    .UseConnectionName("Tracker")
    .AddProviderFactory(NpgsqlFactory.Instance)
    .AddPostgreSqlGenerator()
);

Example

Query all users with email domain. Entity is automatically created from DataReader.

string email = "%@battlestar.com";
string sql = "select * from [User] where EmailAddress like @EmailAddress";

var session = configuration.CreateSession();
var user = await session
    .Sql(sql)
    .Parameter("@EmailAddress", email)
    .QuerySingleAsync(r => new User
    {
        Id = r.GetGuid("Id"),
        EmailAddress = r.GetString("EmailAddress"),
        IsEmailAddressConfirmed = r.GetBoolean("IsEmailAddressConfirmed"),
        DisplayName = r.GetString("DisplayName"),
        PasswordHash = r.GetString("PasswordHash"),
        ResetHash = r.GetString("ResetHash"),
        InviteHash = r.GetString("InviteHash"),
        AccessFailedCount = r.GetInt32("AccessFailedCount"),
        LockoutEnabled = r.GetBoolean("LockoutEnabled"),
        LockoutEnd = r.GetDateTimeOffsetNull("LockoutEnd"),
        LastLogin = r.GetDateTimeOffsetNull("LastLogin"),
        IsDeleted = r.GetBoolean("IsDeleted"),
        Created = r.GetDateTimeOffset("Created"),
        CreatedBy = r.GetString("CreatedBy"),
        Updated = r.GetDateTimeOffset("Updated"),
        UpdatedBy = r.GetString("UpdatedBy"),
        RowVersion = r.GetBytes("RowVersion"),
    });

Execute a stored procedure with out parameters

Guid userId = Guid.Empty;
int errorCode = -1;

var username = "test." + DateTime.Now.Ticks;
var email = username + "@email.com";

var session = configuration.CreateSession();
var result = session
    .StoredProcedure("[dbo].[aspnet_Membership_CreateUser]")
    .Parameter("@ApplicationName", "/")
    .Parameter("@UserName", username)
    .Parameter("@Password", "T@est" + DateTime.Now.Ticks)
    .Parameter("@Email", email)
    .Parameter("@PasswordSalt", "test salt")
    .Parameter<string>("@PasswordQuestion", null)
    .Parameter<string>("@PasswordAnswer", null)
    .Parameter("@IsApproved", true)
    .Parameter("@CurrentTimeUtc", DateTime.UtcNow)
    .Parameter("@UniqueEmail", 1)
    .Parameter("@PasswordFormat", 1)
    .ParameterOut<Guid>("@UserId", p => userId = p)
    .Return<int>(p => errorCode = p)
    .Execute();

Query for user by email address. Also return Role and Status entities.

string email = "kara.thrace@battlestar.com";
string sql = "select * from [User] where EmailAddress = @EmailAddress; " +
             "select * from [Status]; " +
             "select * from [Priority]; ";

User user = null;
List<Status> status = null;
List<Priority> priorities = null;

var session = configuration.CreateSession();
session
    .Sql(sql)
    .Parameter("@EmailAddress", email)
    .QueryMultiple(q =>
    {
        user = q.QuerySingle<User>();
        status = q.Query<Status>().ToList();
        priorities = q.Query<Priority>().ToList();
    });

Query Builder

Build SQL statements with the query builder. Query builder uses the DataAnnotations Schema attributes to extract table and column information.

var session = configuration.CreateSession();

string email = "kara.thrace@battlestar.com";

var user = await session
    .Sql(builder => builder
        .Select<User>() // table name comes from type
        .Where(p => p.EmailAddress, email)
    )
    .QuerySingleAsync<User>();

Count query

string email = "kara.thrace@battlestar.com";

var count = await session
    .Sql(builder => builder
        .Select<User>()
        .Count()
        .Where(p => p.EmailAddress, email)
    )
    .QueryValueAsync<int>();

Insert statement

var id = Guid.NewGuid();

var userId = await session
    .Sql(builder => builder
        .Insert<User>()
        .Value(p => p.Id, id)
        .Value(p => p.EmailAddress, $"{id}@email.com")
        .Value(p => p.DisplayName, "Last, First")
        .Value(p => p.FirstName, "First")
        .Value(p => p.LastName, "Last")
        .Output(p => p.Id) // return key as output value
        .Tag() // add comment tag to query
    )
    .QueryValueAsync<Guid>();

Update statement

var updateId = await session
    .Sql(builder => builder
        .Update<User>()
        .Value(p => p.DisplayName, "Updated Name")
        .Output(p => p.Id)
        .Where(p => p.Id, id)
        .Tag()
    )
    .QueryValueAsync<Guid>();

Delete statement

var deleteId = await session
    .Sql(builder => builder
        .Delete<User>()
        .Output(p => p.Id)
        .Where(p => p.Id, id)
        .Tag()
    )
    .QueryValueAsync<Guid>();

Source Generator

The project supports generating a DbDataReader from a class via an attribute. Add the TableAttribute to a class to generate the needed extension methods.

[Table("Status", Schema = "dbo")]
public class Status
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
    public int DisplayOrder { get; set; }
    public bool IsActive { get; set; }
    public DateTimeOffset Created { get; set; }
    public string CreatedBy { get; set; }
    public DateTimeOffset Updated { get; set; }
    public string UpdatedBy { get; set; }

    [ConcurrencyCheck]
    [DatabaseGenerated(DatabaseGeneratedOption.Computed)]
    [DataFieldConverter(typeof(ConcurrencyTokenHandler))]
    public ConcurrencyToken RowVersion { get; set; }

    [NotMapped]
    public virtual ICollection<Task> Tasks { get; set; } = new List<Task>();
}

Extension methods are generated to materialize data command to entities

string email = "kara.thrace@battlestar.com";
string sql = "select * from [User] where EmailAddress = @EmailAddress";
var session = configuration.CreateSession();
var user = await session
    .Sql(sql)
    .Parameter("@EmailAddress", email)
    .QuerySingleAsync<User>();

SQL Server Features

PM> Install-Package FluentCommand.SqlServer

Bulk Copy

Using SQL Server bulk copy feature to import a lot of data.

using (var session = configuration.CreateSession())
{
    session.BulkCopy("[User]")
        .AutoMap()
        .Ignore("RowVersion")
        .WriteToServer(users);
}

Merge Data

Generate and merge data into a table

var users = generator.List<UserImport>(100);

int rows;
using (var session = configuration.CreateSession())
{
    rows = session
        .MergeData("dbo.User")
        .Map<UserImport>(m => m
            .AutoMap()
            .Column(p => p.EmailAddress).Key()
        )
        .Execute(users);
}
Product Compatible and additional computed target framework versions.
.NET net8.0 is compatible.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed.  net9.0 is compatible.  net9.0-android was computed.  net9.0-browser was computed.  net9.0-ios was computed.  net9.0-maccatalyst was computed.  net9.0-macos was computed.  net9.0-tvos was computed.  net9.0-windows was computed. 
.NET Framework net462 is compatible.  net463 was computed.  net47 was computed.  net471 was computed.  net472 was computed.  net48 was computed.  net481 was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages (1)

Showing the top 1 NuGet packages that depend on FluentCommand.SqlServer:

Package Downloads
FluentCommand.Batch

Fluent Wrapper for DbCommand

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last updated
13.1.0 905 2/16/2025
13.0.0 1,300 11/13/2024
12.13.2 257 9/21/2024
12.13.1 139 9/19/2024
12.13.0 141 9/16/2024
12.12.0 181 9/7/2024
12.11.0 372 8/9/2024
12.10.8 128 8/8/2024
12.10.7 219 7/17/2024
12.10.6 263 7/9/2024
12.10.5 110 7/9/2024
12.10.4 114 6/7/2024
12.10.3 174 5/14/2024
12.10.2 488 5/10/2024
12.10.1 145 5/6/2024
12.10.0 140 5/6/2024
12.9.1 103 5/3/2024
12.9.0 153 4/26/2024
12.8.0 151 4/17/2024
12.7.0 226 3/19/2024
12.6.0 245 2/4/2024
12.5.0 1,216 11/24/2023
12.4.2 171 10/28/2023
12.4.1 207 10/12/2023
12.4.0 140 10/12/2023
12.3.0 5,465 9/14/2023
12.2.0 141 9/14/2023
12.1.0 143 9/13/2023
12.0.0 132 9/12/2023
12.0.0-beta.1 87 9/11/2023
11.0.0 218 8/16/2023
10.2.0 273 8/9/2023
10.1.6 195 7/28/2023
10.1.5 205 7/6/2023
10.0.707 987 3/13/2023
10.0.702 1,078 2/23/2023
10.0.701 389 2/23/2023
10.0.664 824 1/31/2023
10.0.659 492 1/25/2023
10.0.637 693 12/28/2022
10.0.636 439 12/27/2022
10.0.632 532 12/19/2022
10.0.625 460 12/13/2022
10.0.619 582 12/7/2022
10.0.616 529 12/6/2022
10.0.610 521 11/30/2022
9.5.591 761 11/9/2022
9.5.574 550 11/7/2022
9.5.570 532 11/6/2022
9.5.554 773 10/21/2022
9.5.553 630 10/20/2022
9.5.552 678 10/19/2022
9.5.551 633 10/19/2022
9.5.550 619 10/18/2022
9.5.549 628 10/18/2022
9.5.548 651 10/18/2022
9.5.547 594 10/17/2022
9.5.546 598 10/17/2022
9.5.545 635 10/16/2022
9.5.544 617 10/15/2022
9.5.540 625 10/15/2022
9.0.538 691 10/11/2022
9.0.537 645 10/10/2022
9.0.534 649 10/9/2022
9.0.533 624 10/7/2022
9.0.532 671 10/3/2022
9.0.530 685 10/2/2022
9.0.527 675 10/1/2022
9.0.526 639 10/1/2022
9.0.525 661 10/1/2022
9.0.524 644 9/30/2022
9.0.523 658 9/30/2022
9.0.522 677 9/30/2022
9.0.520 675 9/29/2022
9.0.519 698 9/29/2022
9.0.518 671 9/29/2022
9.0.514 706 9/29/2022
8.0.468 839 4/23/2022
8.0.430 498 12/22/2021
8.0.416 518 11/18/2021
7.0.0.393 585 10/21/2021
7.0.0.359 800 4/6/2021
7.0.0.335 590 2/15/2021
7.0.0.296 770 11/16/2020
7.0.0.293 720 11/12/2020
6.0.0.249 838 9/16/2020
6.0.0.240 743 9/5/2020
5.0.0.231 807 8/17/2020
5.0.0.230 793 8/12/2020
5.0.0.220 716 8/10/2020
4.1.0.202 763 6/25/2020
4.1.0.201 759 6/25/2020
4.1.0.186 756 6/15/2020
4.1.0.177 726 6/5/2020
4.1.0.176 718 6/5/2020
4.1.0.167 719 5/29/2020
4.1.0.166 736 5/27/2020
4.1.0.165 790 5/25/2020
4.0.0.148 749 4/11/2020
4.0.0.108 881 12/5/2019
4.0.0.85 743 11/30/2019
4.0.0.83 754 11/29/2019
3.0.0.49 703 5/20/2019