Enhances Entity Framework Core with functional programming patterns and DDD-friendly features. Includes base entity classes, soft delete support, audit trails, query filters, optimistic concurrency, PostgreSQL integration, query performance monitoring, and domain event handling. Perfect for building maintainable and scalable data access layers in modern .NET applications.
$ dotnet add package CSharpEssentials.EntityFrameworkCoreCSharpEssentials is a comprehensive library that enhances C#'s functional programming capabilities. It provides a robust set of tools and utilities designed to make your C# applications more maintainable, testable, and aligned with functional programming principles.
Maybe<T> - Safe handling of nullable values:
Maybe<string> someValue = Maybe.From("Hello");
Maybe<string> noValue = Maybe.None;
// LINQ support
var result = someValue
.Select(str => str.ToUpper())
.Where(str => str.Length > 5);Result<T> - Functional approach to error handling:
public Result<User> CreateUser(UserDto dto)
{
if (string.IsNullOrEmpty(dto.Email))
return Error.Validation("EMAIL_REQUIRED", "Email is required");
var user = new User(dto);
return Result<User>.Success(user);
}RuleEngine - Complex business rule management:
public class EmailValidationRule : IRule<string>
{
public Result Evaluate(string email, CancellationToken cancellationToken = default)
{
return email.Contains("@")
? Result.Success()
: Error.Validation("INVALID_EMAIL", "Email must contain @");
}
}Error - Structured error handling:
var error = Error.Validation(
code: "USER_INVALID_AGE",
description: "User age must be greater than 18"
);Any<T0,T1,...> - Type-safe union types:
public Any<string, int> ParseOrKeepAsString(string input)
{
return int.TryParse(input, out int number)
? number
: input;
}EntityFrameworkCore - Enhanced EF Core support with functional patterns:
public class Product : SoftDeletableEntityBase<Guid>
{
private Product(string name, decimal price)
{
Id = Guid.NewGuid();
Name = name;
Price = price;
}
public static Product Create(string name, decimal price)
{
var product = new Product(name, price);
product.Raise(new ProductCreatedEvent(product.Id));
return product;
}
}
// Configure in DbContext
public void Configure(EntityTypeBuilder<Product> builder)
{
builder.SoftDeletableEntityBaseGuidIdMap();
builder.OptimisticConcurrencyVersionMap();
}DateTimeProvider - Testable datetime handling:
public class OrderService
{
private readonly IDateTimeProvider _dateTimeProvider;
public Order CreateOrder()
{
return new Order { CreatedAt = _dateTimeProvider.UtcNow };
}
}JSON - Enhanced JSON capabilities:
var options = EnhancedJsonSerializerOptions.DefaultOptions;
string json = myObject.ConvertToJson(options);Extensions - Useful extension methods:
// String transformations
"helloWorld".ToPascalCase(); // => "HelloWorld"
"hello_world".ToCamelCase(); // => "helloWorld"
// Collection operations
var randomItem = list.GetRandomItem();RequestResponseLogging - Comprehensive HTTP traffic monitoring:
public void Configure(IApplicationBuilder app)
{
app.AddRequestResponseLogging(opt =>
{
// Configure logging options
var loggingOptions = LoggingOptions.CreateAllFields();
loggingOptions.HeaderKeys.Add("X-Correlation-Id");
// Use the configured logger
opt.UseLogger(app.Services.GetRequiredService<ILoggerFactory>(), loggingOptions);
});
}AspNetCore - Enhanced ASP.NET Core capabilities:
public void ConfigureServices(IServiceCollection services)
{
services
.AddExceptionHandler<GlobalExceptionHandler>()
.ConfigureModelValidatorResponse()
.ConfigureSystemTextJson()
.AddEnhancedProblemDetails()
.AddAndConfigureApiVersioning()
.AddSwagger<DefaultConfigureSwaggerOptions>(
SecuritySchemes.JwtBearerTokenSecurity,
Assembly.GetExecutingAssembly()
);
}
public void Configure(IApplicationBuilder app)
{
app.UseVersionableSwagger();
app.UseExceptionHandler();
app.UseStatusCodePages();
}GcpSecretManager - Seamless integration with Google Cloud Secret Manager:
// Configure in Program.cs or Startup.cs
builder.Configuration.AddGcpSecretManager(options =>
{
options.CredentialsPath = "/path/to/credentials.json";
options.AddProject(new ProjectSecretConfiguration
{
ProjectId = "your-gcp-project-id",
Region = "europe-west1",
PrefixFilters = ["app1_", "app2_"]
});
});
// Or use configuration from appsettings.json
builder.Configuration.AddGcpSecretManager();Choose the packages you need:
dotnet add package CSharpEssentialsdotnet add package CSharpEssentials.EntityFrameworkCoredotnet add package CSharpEssentials.AspNetCoredotnet add package CSharpEssentials.RequestResponseLoggingdotnet add package CSharpEssentials.GcpSecretManagerYou can also install the packages directly from the NuGet Gallery.
Import the required namespaces based on your needs:
// Core functionality
using CSharpEssentials;
// Entity Framework Core integration
using CSharpEssentials.EntityFrameworkCore;
// ASP.NET Core integration
using CSharpEssentials.AspNetCore;
// Request Response Logging
using CSharpEssentials.RequestResponseLogging;Result<T> for operations that can failMaybe<T> over null values for optional valuesError types for domain errorsResult<T>Error.Validation() for input validation failuresError.NotFound() for resource not found scenariosError.Unauthorized() for authentication/authorization failuresEntityBase for domain entitiesRuleEngine for complex validationsIRule<T> for reusable business rulesAny<T0,T1> for type-safe union typesSoftDeletableEntityBase for soft delete supportDateTimeProvider for time-dependent testsResult<T> for predictable error scenariosWe welcome contributions! Please see our Contributing Guide for details.
This project is licensed under the MIT License - see the LICENSE file for details.
This library was inspired by and builds upon the work of several excellent open-source projects:
Special thanks to all contributors who have helped shape this library and to the maintainers of these inspiring projects.
For support, please open an issue in the GitHub repository or contact the maintainers.
Take a look at SenRecep.Aspire, a modern microservices template built with .NET Aspire 9.0. The template provides a robust foundation for building scalable, maintainable, and cloud-ready microservices applications. Check out the GitHub repository for more details.