Facet.Extensions.EFCore 5.8.2

dotnet add package Facet.Extensions.EFCore --version 5.8.2
                    
NuGet\Install-Package Facet.Extensions.EFCore -Version 5.8.2
                    
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="Facet.Extensions.EFCore" Version="5.8.2" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="Facet.Extensions.EFCore" Version="5.8.2" />
                    
Directory.Packages.props
<PackageReference Include="Facet.Extensions.EFCore" />
                    
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 Facet.Extensions.EFCore --version 5.8.2
                    
#r "nuget: Facet.Extensions.EFCore, 5.8.2"
                    
#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.
#:package Facet.Extensions.EFCore@5.8.2
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=Facet.Extensions.EFCore&version=5.8.2
                    
Install as a Cake Addin
#tool nuget:?package=Facet.Extensions.EFCore&version=5.8.2
                    
Install as a Cake Tool

Facet.Extensions.EFCore

EF Core async extension methods for the Facet library, enabling one-line async mapping and projection between your domain entities and generated facet types.

Key Features

  • Forward Mapping: Entity → Facet DTO

    • Async projection to List<TTarget>: ToFacetsAsync<TSource,TTarget>() or ToFacetsAsync<TTarget>()
    • Async projection to first or default: FirstFacetAsync<TSource,TTarget>() or FirstFacetAsync<TTarget>()
    • Async projection to single: SingleFacetAsync<TSource,TTarget>() or SingleFacetAsync<TTarget>()
    • Automatic Navigation Property Loading: No .Include() required for nested facets!
  • Reverse Mapping: Facet DTO → Entity

    • Selective entity updates: UpdateFromFacet<TEntity,TFacet>()
    • Async entity updates: UpdateFromFacetAsync<TEntity,TFacet>()
    • Update with change tracking: UpdateFromFacetWithChanges<TEntity,TFacet>()

All methods leverage your already generated ctor or Projection property and require EF Core 6+.

Getting Started

1. Install packages

dotnet add package Facet.Extensions.EFCore

2. Import namespaces

using Facet.Extensions.EFCore; // for async EF Core extension methods

Forward Mapping (Entity → DTO)

3. Use async mapping in EF Core

// Async projection to list (source type inferred)
var dtos = await dbContext.People.ToFacetsAsync<PersonDto>();

// Async projection to first or default (source type inferred)
var firstDto = await dbContext.People.FirstFacetAsync<PersonDto>();

// Async projection to single (source type inferred)
var singleDto = await dbContext.People.SingleFacetAsync<PersonDto>();

// Legacy explicit syntax still supported
var dtosExplicit = await dbContext.People.ToFacetsAsync<Person, PersonDto>();

4. Automatic Navigation Property Loading (No .Include() Required!)

// Define nested facets
[Facet(typeof(Address))]
public partial record AddressDto;

[Facet(typeof(Company), NestedFacets = [typeof(AddressDto)])]
public partial record CompanyDto;

// Navigation properties are automatically loaded - no .Include() needed!
var companies = await dbContext.Companies
    .Where(c => c.IsActive)
    .ToFacetsAsync<CompanyDto>();

// The HeadquartersAddress navigation property is automatically included!
// EF Core analyzes the projection expression and generates the necessary JOINs

// This also works with collections:
[Facet(typeof(OrderItem))]
public partial record OrderItemDto;

[Facet(typeof(Order), NestedFacets = [typeof(OrderItemDto), typeof(AddressDto)])]
public partial record OrderDto;

var orders = await dbContext.Orders
    .ToFacetsAsync<OrderDto>();  // Automatically includes Items collection and ShippingAddress!

// All these methods support auto-include:
await dbContext.Companies.ToFacetsAsync<CompanyDto>();
await dbContext.Companies.FirstFacetAsync<CompanyDto>();
await dbContext.Companies.SingleFacetAsync<CompanyDto>();
await dbContext.Companies.SelectFacet<CompanyDto>().ToListAsync();

Streaming with AsAsyncEnumerable

Facet fully supports EF Core's streaming patterns using AsAsyncEnumerable() for memory-efficient processing of large result sets:

// Stream results one at a time instead of loading all into memory
await foreach (var userDto in dbContext.Users
    .Where(u => u.IsActive)
    .SelectFacet<UserDto>()        // Apply facet projection
    .AsAsyncEnumerable())           // Stream results
{
    // Process each item as it's retrieved from the database
    await ProcessUserAsync(userDto);
}

// Works with complex queries
await foreach (var companyDto in dbContext.Companies
    .Where(c => c.Revenue > 1000000)
    .OrderBy(c => c.Name)
    .SelectFacet<CompanyDto>()      // Nested facets are automatically loaded
    .AsAsyncEnumerable())
{
    Console.WriteLine($"{companyDto.Name}: {companyDto.HeadquartersAddress?.City}");
}

// Memory-efficient pagination
await foreach (var productDto in dbContext.Products
    .OrderBy(p => p.Id)
    .Skip(page * pageSize)
    .Take(pageSize)
    .SelectFacet<ProductDto>()
    .AsAsyncEnumerable())
{
    yield return productDto;
}

Important: Always call SelectFacet() before AsAsyncEnumerable():

  • Correct: .SelectFacet<Dto>().AsAsyncEnumerable() - Projection happens in SQL
  • Incorrect: .AsAsyncEnumerable().Select(x => x.ToFacet<Dto>()) - Loads full entities into memory first

The correct order ensures that:

  1. The projection is translated to SQL (efficient database query)
  2. Only the projected columns are retrieved from the database
  3. Results are streamed without loading everything into memory

Reverse Mapping (DTO → Entity)

4. Use selective entity updates

// Define update DTO (excludes sensitive/immutable properties)
[Facet(typeof(User), "Password", "CreatedAt")]
public partial class UpdateUserDto { }

// API Controller
[HttpPut("{id}")]
public async Task<IActionResult> UpdateUser(int id, UpdateUserDto dto)
{
    var user = await context.Users.FindAsync(id);
    if (user == null) return NotFound();
    
    // Only updates properties that actually changed
    user.UpdateFromFacet(dto, context);
    
    await context.SaveChangesAsync();
    return NoContent();
}

5. Advanced scenarios

// With change tracking for auditing
var result = user.UpdateFromFacetWithChanges(dto, context);
if (result.HasChanges)
{
    logger.LogInformation("User {UserId} updated. Changed: {Properties}", 
        user.Id, string.Join(", ", result.ChangedProperties));
}

// Async version (for future extensibility)
await user.UpdateFromFacetAsync(dto, context);

Complete Example

// Domain entity
public class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
    public decimal Price { get; set; }
    public DateTime CreatedAt { get; set; }  // Immutable
    public string InternalNotes { get; set; }  // Sensitive
}

// Read DTO (for GET operations)
[Facet(typeof(Product), "InternalNotes")]
public partial class ProductDto { }

// Update DTO (for PUT operations - excludes immutable/sensitive fields)
[Facet(typeof(Product), "Id", "CreatedAt", "InternalNotes")]
public partial class UpdateProductDto { }

// API Controller
[ApiController]
[Route("api/[controller]")]
public class ProductsController : ControllerBase
{
    private readonly ApplicationDbContext _context;
    
    public ProductsController(ApplicationDbContext context)
    {
        _context = context;
    }
    
    // GET: Forward mapping (Entity -> DTO)
    [HttpGet]
    public async Task<ActionResult<IEnumerable<ProductDto>>> GetProducts()
    {
        return await _context.Products
            .Where(p => p.IsActive)
            .ToFacetsAsync<ProductDto>();  // Source type inferred
    }
    
    [HttpGet("{id}")]
    public async Task<ActionResult<ProductDto>> GetProduct(int id)
    {
        var product = await _context.Products
            .Where(p => p.Id == id)
            .FirstFacetAsync<ProductDto>();  // Source type inferred
            
        return product == null ? NotFound() : product;
    }
    
    // PUT: Reverse mapping (DTO -> Entity)
    [HttpPut("{id}")]
    public async Task<IActionResult> UpdateProduct(int id, UpdateProductDto dto)
    {
        var product = await _context.Products.FindAsync(id);
        if (product == null) return NotFound();
        
        // Selective update - only changed properties
        var result = product.UpdateFromFacetWithChanges(dto, _context);
        
        if (result.HasChanges)
        {
            await _context.SaveChangesAsync();
            
            // Optional: Log what changed
            logger.LogInformation("Product {ProductId} updated. Changed: {Properties}", 
                id, string.Join(", ", result.ChangedProperties));
        }
        
        return NoContent();
    }
}

Advanced: Custom Mapping Support

For complex mappings that cannot be expressed as SQL projections (e.g., calling external services, complex type conversions like Vector2, or async operations), see the Facet.Extensions.EFCore.Mapping package.

dotnet add package Facet.Extensions.EFCore.Mapping

This optional package provides custom async mapper support with dependency injection for advanced scenarios. See the Facet.Extensions.EFCore.Mapping README for details.

API Reference

Method Description Use Case
ToFacetsAsync<TTarget>() Project query to DTO list (source inferred) GET endpoints
ToFacetsAsync<TSource, TTarget>() Project query to DTO list (explicit types) Legacy/explicit typing
FirstFacetAsync<TTarget>() Get first DTO or null (source inferred) GET single item
FirstFacetAsync<TSource, TTarget>() Get first DTO or null (explicit types) Legacy/explicit typing
SingleFacetAsync<TTarget>() Get single DTO (source inferred) GET unique item
SingleFacetAsync<TSource, TTarget>() Get single DTO (explicit types) Legacy/explicit typing
SelectFacet<TTarget>().AsAsyncEnumerable() Stream projected results Memory-efficient large result sets
SelectFacet<TSource, TTarget>().AsAsyncEnumerable() Stream projected results (explicit) Memory-efficient large result sets
UpdateFromFacet<TEntity, TFacet>() Selective entity update PUT/PATCH endpoints
UpdateFromFacetWithChanges<TEntity, TFacet>() Update with change tracking Auditing scenarios
UpdateFromFacetAsync<TEntity, TFacet>() Async selective update Future extensibility

For custom async mapper overloads, see Facet.Extensions.EFCore.Mapping.

Requirements

  • Facet v1.6.0+
  • Entity Framework Core 6+
  • .NET 6+
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.  net10.0 is compatible.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows 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 Facet.Extensions.EFCore:

Package Downloads
Facet.Extensions.EFCore.Mapping

Advanced custom async mapper support for Facet with EF Core queries. Enables complex mappings that cannot be expressed as SQL projections.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
5.8.2 52 3/5/2026
5.8.1 44 3/4/2026
5.8.0 39 3/4/2026
5.7.0 286 2/24/2026
5.6.5 235 2/22/2026
5.6.4 158 2/20/2026
5.6.3 289 2/19/2026
5.6.2 187 2/15/2026
5.6.1 123 2/13/2026
5.6.0 115 2/12/2026
5.5.3 110 2/12/2026
5.5.2 260 1/29/2026
5.5.1 124 1/28/2026
5.5.0 121 1/27/2026
5.4.4 115 1/27/2026
5.4.3 281 1/23/2026
5.4.2 122 1/22/2026
5.4.1 1,331 1/13/2026
5.4.0 128 1/12/2026
5.3.3 115 1/12/2026
Loading failed