EntityFrameworkCore.Extensions
10.3.2
dotnet add package EntityFrameworkCore.Extensions --version 10.3.2
NuGet\Install-Package EntityFrameworkCore.Extensions -Version 10.3.2
<PackageReference Include="EntityFrameworkCore.Extensions" Version="10.3.2" />
<PackageVersion Include="EntityFrameworkCore.Extensions" Version="10.3.2" />
<PackageReference Include="EntityFrameworkCore.Extensions" />
paket add EntityFrameworkCore.Extensions --version 10.3.2
#r "nuget: EntityFrameworkCore.Extensions, 10.3.2"
#:package EntityFrameworkCore.Extensions@10.3.2
#addin nuget:?package=EntityFrameworkCore.Extensions&version=10.3.2
#tool nuget:?package=EntityFrameworkCore.Extensions&version=10.3.2
EntityFrameworkCore.Extensions
SQL Server features that EF Core 10 has no built-in API for, configured in the model and in LINQ:
- Dynamic data masking:
HasDataMaskmasks a column, so users without theUNMASKpermission read+1XX-XX8where+12345678is stored. - Spatial indexes:
HasSpatialIndexcreates an index on ageographyorgeometrycolumn, with bounding box and cells-per-object options. - Columnstore indexes:
HasColumnstoreIndexcreates a nonclustered columnstore index on the columns you select, with an optional filter. - Query and table hints:
WithQueryHintsandWithTableHintsaddOPTION (...)andWITH (...)to a LINQ query, for hints such asRECOMPILE,MAXDOP,NOLOCK,UPDLOCKandREADPAST. - Helpers:
MigrateIfSupportedfor providers without migrations,SqlFilefor SQL files in migrations, andOverrideDeleteBehaviourfor a model-wide delete behavior.
Indexes and masks are part of the model, so migrations create, change and drop them.
Installation
dotnet add package EntityFrameworkCore.Extensions
services.AddDbContext<AppDbContext>(options => options
.UseSqlServer(connectionString)
.UseEntityFrameworkCoreExtensions());
- Requires EF Core 10, .NET 10 and SQL Server 2016 or later.
UseEntityFrameworkCoreExtensions()can be called before or afterUseSqlServer, and also inOnConfiguring.- Sample project: EntityFrameworkCore.Extensions.Samples.
Dynamic data masking
HasDataMask applies a dynamic data masking function to a column. Users without the UNMASK permission read masked values. The stored data is unchanged.
modelBuilder.Entity<Customer>(customer =>
{
customer.Property(c => c.Surname).HasDataMask(MaskingFunctions.Default());
customer.Property(c => c.Email).HasDataMask(MaskingFunctions.Email());
customer.Property(c => c.Phone).HasDataMask(MaskingFunctions.Partial(2, "XX-XX", 1));
customer.Property(c => c.DiscountCardNumber).HasDataMask(MaskingFunctions.Random(10, 100));
});
| Function | Stored value | Read without UNMASK |
|---|---|---|
Default() |
Smith |
xxxx |
Email() |
smith@example.com |
sXXX@XXXX.com |
Partial(2, "XX-XX", 1) |
+12345678 |
+1XX-XX8 |
Random(10, 100) |
12881234 |
a random number from 10 to 100 |
- Migrations add, replace and drop masks as the model changes.
HasDataMaskaccepts any masking function as a string, for exampleHasDataMask("datetime(\"Y\")")on SQL Server 2022 or later.- Permissions are not modeled. Grant
UNMASKin SQL. Members ofdb_owneralways read the stored values.
Spatial indexes
HasSpatialIndex creates a spatial index on a geography or geometry column. It requires the Microsoft.EntityFrameworkCore.SqlServer.NetTopologySuite package and UseNetTopologySuite() in UseSqlServer.
modelBuilder.Entity<Place>()
.HasSpatialIndex(p => p.Location);
modelBuilder.Entity<Region>(region =>
{
region.Property(r => r.Boundary).HasColumnType("geometry");
region.HasSpatialIndex(
r => r.Boundary,
spatial => spatial.HasBoundingBox(-180, -90, 180, 90).HasCellsPerObject(32))
.HasDatabaseName("SIX_Regions_Boundary");
});
CREATE SPATIAL INDEX [IX_Places_Location] ON [Places] ([Location])
USING GEOGRAPHY_AUTO_GRID;
CREATE SPATIAL INDEX [SIX_Regions_Boundary] ON [Regions] ([Boundary])
USING GEOMETRY_AUTO_GRID
WITH (BOUNDING_BOX = (-180, -90, 180, 90), CELLS_PER_OBJECT = 32);
- NetTopologySuite properties map to
geographyby default. SetHasColumnType("geometry")forgeometry. - A
geometryindex requiresHasBoundingBox. Ageographyindex does not accept one.HasCellsPerObjectis optional. - Overloads accept property names as strings, owned types, and a model index name for a second index on the same property.
Columnstore indexes
HasColumnstoreIndex creates a nonclustered columnstore index with an optional filter.
modelBuilder.Entity<Order>()
.HasColumnstoreIndex(o => new { o.Created, o.Amount })
.HasDatabaseName("NCCI_Orders_Reporting")
.HasFilter("[Amount] > 0");
CREATE NONCLUSTERED COLUMNSTORE INDEX [NCCI_Orders_Reporting]
ON [Orders] ([Created], [Amount])
WHERE [Amount] > 0;
- Changing the columns or the filter drops and recreates the index. Changing the database name renames it.
- A string property without a configured length becomes
nvarchar(450), as for any index. SetHasMaxLengthto control it. - To keep a rowstore index on the same columns, pass a model index name:
.HasColumnstoreIndex(o => new { o.Created, o.Amount }, "Reporting"). - Overloads accept property names as strings and owned types.
Query and table hints
WithQueryHints appends one OPTION (...) clause to the statement. WithTableHints adds WITH (...) to every table in the statement, including joined tables and subqueries. SQL Server documents each query hint and table hint.
var orders = await context.Orders
.Where(o => o.CustomerId == customerId)
.WithQueryHints(QueryHint.Recompile())
.WithTableHints(TableHint.NoLock())
.ToListAsync();
SELECT [o].[Id], [o].[Amount], [o].[Created], [o].[CustomerId]
FROM [Orders] AS [o] WITH (NOLOCK)
WHERE [o].[CustomerId] = @customerId
OPTION (RECOMPILE)
Locking hints, inside a transaction:
await using var transaction = await context.Database.BeginTransactionAsync();
var job = await context.Jobs
.Where(j => j.StartedAt == null)
.OrderBy(j => j.Id)
.WithTableHints(TableHint.UpdLock(), TableHint.ReadPast(), TableHint.RowLock())
.FirstOrDefaultAsync();
if (job is not null)
{
job.StartedAt = DateTime.UtcNow;
await context.SaveChangesAsync();
}
await transaction.CommitAsync();
SELECT TOP(1) [j].[Id], [j].[Payload], [j].[StartedAt]
FROM [Jobs] AS [j] WITH (UPDLOCK, READPAST, ROWLOCK)
WHERE [j].[StartedAt] IS NULL
ORDER BY [j].[Id]
- Hints apply to
Includejoins, every command of a split query,ExecuteUpdate,ExecuteDeleteand temporal tables. Hint calls inside compiled queries, correlated subqueries and global query filters are supported. - Hint arguments are validated. Combinations that SQL Server rejects, such as
NOLOCKwithUPDLOCKor twoMAXDOPvalues, throw before a command is sent. - Both methods throw when
UseEntityFrameworkCoreExtensions()is not configured. The InMemory provider ignores hints. - Locking hints such as
UPDLOCKhold their locks until the transaction ends.
Supported hints
Query hints (QueryHint): RECOMPILE, MAXDOP, MAXRECURSION, OPTIMIZE FOR UNKNOWN, FORCE ORDER, HASH JOIN, LOOP JOIN, MERGE JOIN, HASH GROUP, ORDER GROUP, CONCAT UNION, HASH UNION, MERGE UNION, FAST, KEEP PLAN, KEEPFIXED PLAN, ROBUST PLAN, EXPAND VIEWS, NO_PERFORMANCE_SPOOL, IGNORE_NONCLUSTERED_COLUMNSTORE_INDEX, MAX_GRANT_PERCENT, MIN_GRANT_PERCENT, and any USE HINT name.
Table hints (TableHint): NOLOCK, READUNCOMMITTED, READCOMMITTED, READCOMMITTEDLOCK, REPEATABLEREAD, SERIALIZABLE, HOLDLOCK, UPDLOCK, XLOCK, ROWLOCK, PAGLOCK, TABLOCK, TABLOCKX, READPAST, NOWAIT, FORCESEEK, FORCESCAN.
Factory methods use the matching names, for example QueryHint.OptimizeForUnknown(), QueryHint.MaxDop(4), QueryHint.UseHint("DISABLE_PARAMETER_SNIFFING") and TableHint.ReadPast().
Helpers
MigrateIfSupported
Applies pending migrations. On a provider without migrations, such as InMemory, it does nothing, whereas Migrate() throws.
await context.Database.MigrateIfSupportedAsync();
SqlFile
Adds the contents of a SQL file to a migration. The file is read when the migration is applied or scripted, so it must be copied to the output directory and addressed from AppContext.BaseDirectory.
migrationBuilder.SqlFile(
Path.Combine(AppContext.BaseDirectory, "SqlFiles", "ImportCustomers.sql"));
<None Update="SqlFiles/ImportCustomers.sql" CopyToOutputDirectory="PreserveNewest" />
OverrideDeleteBehaviour
Sets the delete behavior of every foreign key that is already in the model. Call it at the end of OnModelCreating. The default argument is Restrict.
modelBuilder.OverrideDeleteBehaviour(DeleteBehavior.Restrict);
Limitations
Unsupported model configurations are rejected when the migration is generated. Unsupported hints throw before a command is sent.
Spatial indexes
- The table must have a clustered primary key, which is the EF Core default.
- An index covers one column and uses auto-grid tessellation.
- Only
HasDatabaseName()can be chained. Unique, filtered, included-column, descending and other index options are rejected.
Columnstore indexes
- SQL Server allows one columnstore index per table. An index can have up to 1,024 columns.
- Only nonclustered columnstore indexes are created. Clustered and ordered columnstore indexes are not available.
- Only
HasDatabaseName()andHasFilter()can be chained. Uniqueness, included columns, sort order,ONLINEand compression are rejected. - Supported column types are numeric,
bit, date and time,uniqueidentifier, and string and binary types with a bounded length. Computed columns, sparse columns and memory-optimized tables are rejected. - Database requirements are listed in SQL Server's CREATE COLUMNSTORE INDEX documentation.
Query and table hints
- Table hints apply to every table in the statement. A single table cannot be targeted.
- Index hints are not available.
- Uncomposed
FromSqlandSqlQueryqueries reject hints. Composed ones accept query hints only. Queries over table-valued functions reject table hints.
Compatibility
- CI runs the integration tests against SQL Server 2016 and SQL Server 2025.
- With the InMemory provider the registration is inert: the model builds, hints are ignored and
MigrateIfSupporteddoes nothing. Other relational providers are rejected with anInvalidOperationException. UseEntityFrameworkCoreExtensions()replaces six EF Core services:IMigrationsSqlGenerator,IRelationalAnnotationProvider,IQuerySqlGeneratorFactory,IRelationalParameterBasedSqlProcessorFactory,IQueryTranslationPreprocessorFactoryandIQueryCompiler. If another registration replaces one of them, the last one takes effect.
Roadmap
GRANTandREVOKE UNMASKfor dynamic data masking.- Row-level security.
- Ledger tables.
Release notes
License
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | 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. |
-
net10.0
- Microsoft.Data.SqlClient (>= 6.1.8 && < 7.0.0)
- Microsoft.EntityFrameworkCore.SqlServer (>= 10.0.12 && < 11.0.0)
NuGet packages
This package is not used by any NuGet packages.
GitHub repositories
This package is not used by any popular GitHub repositories.
| Version | Downloads | Last Updated |
|---|---|---|
| 10.3.2 | 144 | 11/15/2026 |
| 10.3.1 | 720 | 10/6/2026 |
| 10.3.0 | 115 | 10/6/2026 |
| 10.2.0 | 5,423 | 9/9/2026 |
| 10.1.0 | 173 | 9/5/2026 |
| 10.0.1 | 392 | 8/26/2026 |
| 10.0.0 | 211 | 8/20/2026 |
| 10.0.0-beta.1 | 107 | 8/18/2026 |
| 5.0.0 | 835,276 | 8/8/2021 |
| 5.0.0-beta | 991 | 7/28/2021 |
| 3.2.1 | 8,958 | 3/21/2021 |
| 3.2.0 | 124,887 | 3/28/2020 |
| 3.1.2 | 2,946 | 3/22/2020 |
| 1.0.2 | 7,273 | 7/9/2018 |
| 1.0.1 | 2,080 | 6/19/2018 |
| 1.0.0 | 2,080 | 6/16/2018 |