获取 asp.net 样板存储库使用的 DbContext 实例

Get DbContext Instance used by asp.net boilerplate repository

我使用 Aspnet Boiler plate 开始了一个新项目,但不再喜欢使用存储库和在幕后完成的大量隐藏工程。

Hence looking forward to get instance the db context instantiated by Abp repositories framework and

  1. 直接使用 Ef 核心 LINQ 查询。
  2. 直接使用 SaveChanges 提交我的更改,而不是依赖 抽象交易。

请问我如何获取该实例?

  1. work with Ef core LINQ queries directly.

您可以使用 IDbContextProviderGetDbContext() 获取 DbContext 的实例。

private readonly YourDbContext _ctx;

public YourService(IDbContextProvider<YourDbContext> dbContextProvider)
{
    _ctx = dbContextProvider.GetDbContext();
}
  1. Commit my changes directly using SaveChanges, rather than relying on abstracted transactions.

您可以通过应用 [UnitOfWork(IsDisabled = true)] 属性来禁用交易

Here 是一篇有关使用 ASP.NET 样板进行事务管理的相关文章。

@NitinSawant 我有一个类似的问题,但在我的例子中,有问题的参数被特别称为 unitOfWork。我有一个数据库清理和更新种子助手 class,它是 运行 来自模块的 Postinitialize 方法:

public override void PostInitialize()
{
    // The hypothetical 'SweeperClass' in this example uses constructor
    // injection to obtain a IDbContextProvider instance and from there
    // get hold of a DbContext.
    //
    // As written, this code threw a null argument exception.

    var sweeperClass = IocManager.Resolve<SweeperClass>();
    // ...do stuff...
}

在这种情况下,幸运的是,这只是一个解决工作单元以包装另一个对象构造的问题。

using Abp.Domain.Uow;

public override void PostInitialize()
{
    using (IocManager.Resolve<IUnitOfWorkManager>().Begin())
    {
        var sweeperClass = IocManager.Resolve<SweeperClass>();
        // ...do stuff...
    }
}

所以@koryakinp 的回答为我提供了大部分解决方案,我只需要进行上述调整即可针对我的特定用例进行操作。