Euonia.Repository.EfCore
2026.5.0
dotnet add package Euonia.Repository.EfCore --version 2026.5.0
NuGet\Install-Package Euonia.Repository.EfCore -Version 2026.5.0
<PackageReference Include="Euonia.Repository.EfCore" Version="2026.5.0" />
<PackageVersion Include="Euonia.Repository.EfCore" Version="2026.5.0" />
<PackageReference Include="Euonia.Repository.EfCore" />
paket add Euonia.Repository.EfCore --version 2026.5.0
#r "nuget: Euonia.Repository.EfCore, 2026.5.0"
#:package Euonia.Repository.EfCore@2026.5.0
#addin nuget:?package=Euonia.Repository.EfCore&version=2026.5.0
#tool nuget:?package=Euonia.Repository.EfCore&version=2026.5.0
Euonia.Repository.EfCore
Euonia 仓储抽象的 Entity Framework Core 实现:提供 DataContextBase<TContext> 上下文基类与 EfCoreRepository<TContext, TEntity, TKey> 仓储,并通过 AddEfCoreRepository 注册上下文、仓储与工作单元上下文工厂。
- 目标框架:
net10.0、net11.0 - 根命名空间:
Nerosoft.Euonia.Repository.EfCore - NuGet 包:
Euonia.Repository.EfCore
安装
dotnet add package Euonia.Repository.EfCore
快速开始
定义上下文:
using Microsoft.EntityFrameworkCore;
using Nerosoft.Euonia.Repository.EfCore;
public sealed class AppDbContext(DbContextOptions<AppDbContext> options)
: DataContextBase<AppDbContext>(options)
{
protected override bool AutoSetEntryValues => true;
public DbSet<Order> Orders => Set<Order>();
}
注册仓储:
using Microsoft.Extensions.DependencyInjection;
using Nerosoft.Euonia.Repository;
using Nerosoft.Euonia.Repository.EfCore;
services.AddContextProvider();
services.AddEfCoreRepository<AppDbContext>(options =>
{
options.UseNpgsql(configuration.GetConnectionString("Default"));
});
也可使用
AddEfCoreRepository<TContextService, TContextImplementation>(...)、带IServiceProvider的重载,以及只注册开放式泛型仓储的AddEfCoreRepository(ServiceLifetime)。
使用仓储:
using Nerosoft.Euonia.Repository;
public sealed class OrderService(IRepository<AppDbContext, Order, long> repository)
{
public Task<Order?> GetAsync(long id, CancellationToken cancellationToken)
=> repository.GetAsync(id, cancellationToken);
public async Task<Order> CreateAsync(Order order, CancellationToken cancellationToken)
=> await repository.InsertAsync(order, autoSave: true, cancellationToken);
}
主要功能
- 上下文基类:
DataContextBase<TContext>实现IRepositoryContext,提供SetEntryValues与ConfigureModel钩子。 - 仓储实现:
EfCoreRepository<TContext, TEntity, TKey>基于IRepositoryContext+DbSet完成查询与 CRUD,并记录仓储遥测。 - 统一注册:
AddEfCoreRepository注册DbContext与开放式泛型仓储,并注册UnitOfWorkContextFactory。 - 连接串解析:
AddDataContextFactory<TContext>按名称、上下文类型名、Default、解析器与代码默认值依次解析。 - 工作单元:
UnitOfWorkContext/UnitOfWorkContextFactory在事务性工作单元中复用上下文并开启事务。 - 值转换与生成:
UniversalTimeConverter、SnowflakeIdValueGenerator、GuidVersion7ValueGenerator、UlidValueGenerator等。 - 查询扩展:
Include/IncludeIf/Tracking/Attach(EF Core 专用)。 - 多租户:
MultiTenantDataContextBase<TContext>、TenantConnectionStringResolver<TContext>等。
使用示例
按连接串名称解析并注册上下文工厂({provider}://{connection} 前缀用于选择已注册的 ConnectionConfigurator):
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Nerosoft.Euonia.Modularity;
using Nerosoft.Euonia.Repository;
using Nerosoft.Euonia.Repository.EfCore;
[ConnectionString(Name = "Default")]
public sealed class AppDbContext(DbContextOptions<AppDbContext> options)
: DataContextBase<AppDbContext>(options)
{
protected override bool AutoSetEntryValues => true;
}
[DependsOn(typeof(RepositoryModule))]
public sealed class PersistModule : ModuleContextBase
{
public override void ConfigureServices(ServiceConfigurationContext context)
{
context.Services.AddKeyedSingleton<ConnectionConfigurator>("sqlite",
(builder, connection) => builder.UseSqlite(connection));
context.Services.AddDataContextFactory<AppDbContext>();
}
}
AddEfCoreRepository只接收Action<DbContextOptionsBuilder>,不读取ConnectionStrings;需要按配置/环境变量解析时使用AddDataContextFactory<TContext>。
配置项
AddDataContextFactory<TContext>() 的连接串解析顺序:
| 优先级 | 来源 | 说明 |
|---|---|---|
| 1 | 显式 connectionStringFactory |
调用方直接返回连接串 |
| 2 | ConnectionStrings:<ConnectionStringAttribute.Name> |
上下文特性上的名称 |
| 3 | ConnectionStrings:<TContext 类型名> |
如 ConnectionStrings:AppDbContext |
| 4 | ConnectionStrings:Default |
通用回退 |
| 5 | IConnectionStringResolver<TContext> |
异步解析器 |
| 6 | ConnectionStringAttribute.Value |
代码默认值 |
{
"ConnectionStrings": {
"Default": "sqlite://Data Source=app.db"
}
}
ConnectionStrings__Default="sqlite://Data Source=app.db" # .NET 原生
CONNECTION_STRING_DEFAULT="sqlite://Data Source=app.db" # 仓库 alias
代码选项
| 成员 | 默认值 | 说明 |
|---|---|---|
AutoSetEntryValues |
抽象属性 | 保存时是否调用 SetEntryValues;派生类必须重写 |
DateTimeKind |
Unspecified |
派生类在 SetEntryValues 中写入日期时间时使用的 Kind |
contextLifeTime |
Scoped |
AddEfCoreRepository / AddDataContextFactory 的生命周期参数 |
SetEntryValues |
空实现 | 保存前填充审计字段等;基类不做任何填充 |
ConfigureModel |
空实现 | 在软删除过滤器之后追加模型配置 |
本包没有
Euonia:Repository配置节;除ConnectionStrings外均为代码配置。
核心类型
| 类型 | 作用 |
|---|---|
DataContextBase<TContext> |
EF Core 上下文基类 |
EfCoreRepository<TContext, TEntity, TKey> |
EF Core 仓储实现 |
UnitOfWorkContext / UnitOfWorkContextFactory(internal) |
工作单元上下文与工厂,由 DI 注册 |
AddEfCoreRepository<TContext>(...) |
注册上下文与仓储 |
AddDataContextFactory<TContext>(...) |
按连接串解析注册 IDbContextFactory<TContext> |
ConnectionConfigurator |
(DbContextOptionsBuilder, string) -> DbContextOptionsBuilder 委托 |
DataContextExtensions |
GetTableName、GetForeignKey、SetTombstoneQueryFilter |
RepositoryExtensions |
EF Core 专用 Include / IncludeIf / Tracking / Attach |
UniversalTimeConverter / SnowflakeIdValueGenerator / GuidVersion7ValueGenerator / UlidValueGenerator |
值转换与值生成器 |
注意事项 / 限制
AddEfCoreRepository不注册IContextProvider;需要[DependsOn(typeof(RepositoryModule))]或显式services.AddContextProvider(),否则解析仓储会失败。AddEfCoreRepository不解析ConnectionStrings;要使用名称回退、环境变量与{provider}://前缀,请改用AddDataContextFactory<TContext>()。DataContextBase.OnModelCreating只应用带[DbContext(typeof(TContext))]的IEntityTypeConfiguration;没有该特性的配置不会被加载。AutoSetEntryValues => true只会调用SetEntryValues;基类实现为空,审计字段需要派生类自己填充。- 软删除过滤器以命名过滤器
TenantFilterNames.Tombstone注册;EF Core 不允许命名与匿名查询过滤器混用。 AddDataContextFactory要求连接串带{provider}://前缀,并为该 provider 注册键控ConnectionConfigurator;否则抛NotSupportedException。AddEfCoreRepository<TContext>(..., ServiceLifetime.Singleton)会把DbContext注册为单例,AddEfCoreRepository(ServiceLifetime.Singleton)会把开放式仓储注册为单例;两者都与 EF Core 的线程模型冲突,生产环境应保持Scoped。UnitOfWorkContextFactory只在IUnitOfWork.Options.IsTransactional为true时开启事务;非事务性工作单元直接解析上下文,不会提交/回滚。
相关包
Euonia.Repository—— 仓储抽象Euonia.Repository.Mongo—— MongoDB 实现Euonia.Uow—— 工作单元Euonia.Linq—— 查询与规约Euonia.Tenancy—— 多租户过滤器与连接串
常见问题与故障排查
解析仓储时报 Unable to resolve service for type 'IContextProvider'
AddEfCoreRepository 只注册 DbContext、开放式仓储与 IContextFactory,不会注册 IContextProvider。在模块上添加 [DependsOn(typeof(RepositoryModule))],或显式调用 services.AddContextProvider()。
AddDataContextFactory 抛 ArgumentException / NotSupportedException
连接串必须带 {provider}:// 前缀,例如 sqlite://Data Source=app.db;前缀对应的 provider 还必须注册键控 ConnectionConfigurator。缺少前缀会抛 ArgumentException,provider 未注册会抛 NotSupportedException。
AutoSetEntryValues => true,审计字段仍为空
DataContextBase 只提供 SetEntryValues 钩子,基类实现为空;AutoSetEntryValues 为 true 仅表示保存前调用它。需要在派生上下文中重写 SetEntryValues 并填充 CreatedAt/UpdatedAt 等字段。
实体配置没有生效
DataContextBase.OnModelCreating 只加载带 [DbContext(typeof(TContext))] 的 IEntityTypeConfiguration。没有该特性、或指向其他上下文类型的配置不会被应用。
ValidateScopes 下启动失败
把 DbContext 或仓储注册为 Singleton 会与 EF Core 的线程模型冲突;AddEfCoreRepository<TContext>(..., ServiceLifetime.Singleton) 与 AddEfCoreRepository(ServiceLifetime.Singleton) 都可能触发。生产环境保持 Scoped。
最佳实践
- 模块同时使用
[DependsOn(typeof(RepositoryModule))]与AddDataContextFactory<TContext>(),让连接串按名称/环境变量解析。 - 每个 provider 注册一个键控
ConnectionConfigurator(如"sqlite"),连接串用ConnectionStrings__Default或CONNECTION_STRING_DEFAULT覆盖。 - 迁移与建库放在部署阶段;不要在请求路径里
EnsureCreated。 - 派生上下文重写
SetEntryValues与ConfigureModel,保持审计字段、软删除过滤器和租户过滤器顺序一致。
版本与兼容
- 目标框架:
net10.0、net11.0(Source/common.props)。 - 关键依赖:
Euonia.Repository、Euonia.Uow、Microsoft.EntityFrameworkCore/Relational;具体版本由仓库构建属性决定。 - 已知边界:
AddEfCoreRepository不解析ConnectionStrings;DataContextBase的审计填充是空钩子;软删除使用命名过滤器,不能与匿名过滤器混用。
许可证
本项目依据仓库根目录的 GNU General Public License v3.0 发布。
| 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. net11.0 is compatible. |
-
net10.0
- Euonia.Repository (>= 2026.5.0)
- Euonia.Tenancy (>= 2026.5.0)
- Microsoft.EntityFrameworkCore (>= 10.0.15 && < 11.0.0)
- Microsoft.EntityFrameworkCore.Relational (>= 10.0.15 && < 11.0.0)
-
net11.0
- Euonia.Repository (>= 2026.5.0)
- Euonia.Tenancy (>= 2026.5.0)
- Microsoft.EntityFrameworkCore (>= 11.0.0 && < 12.0.0)
- Microsoft.EntityFrameworkCore.Relational (>= 11.0.0 && < 12.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 |
|---|---|---|
| 2026.5.0 | 200 | 11/13/2026 |
| 2026.4.7 | 133 | 11/3/2026 |
| 2026.4.6 | 109 | 10/28/2026 |
| 2026.4.5 | 135 | 10/19/2026 |
| 2026.4.4 | 112 | 10/19/2026 |
| 2026.4.3 | 139 | 10/1/2026 |
| 2026.4.1 | 125 | 9/24/2026 |
| 2026.4.0 | 133 | 9/22/2026 |
| 2026.3.16 | 153 | 9/8/2026 |
| 2026.3.15 | 140 | 9/2/2026 |
| 2026.3.14 | 134 | 8/30/2026 |
| 2026.3.13 | 142 | 8/29/2026 |
| 2026.3.12 | 133 | 8/28/2026 |
| 2026.3.11 | 135 | 8/27/2026 |
| 2026.3.10 | 147 | 8/26/2026 |
| 2026.3.9 | 141 | 8/25/2026 |
| 2026.3.8 | 144 | 8/24/2026 |
| 2026.3.7 | 142 | 8/20/2026 |
| 2026.3.6 | 125 | 8/20/2026 |
| 2026.3.5 | 142 | 8/19/2026 |