3

I started a new project using Aspnet Boiler plate, but no longer feel like using repositories and tons of hidden engineering done behind the scene.

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

  1. work with Ef core LINQ queries directly.
  2. Commit my changes directly using SaveChanges, rather than relying on abstracted transactions.

How do I fetch that instance please?

Abhijeet
  • 13,562
  • 26
  • 94
  • 175
  • asp.net boilerplate (I presume that's what abp stands for) is a repository pattern used to abstract the used DbContext instance. – DevilSuichiro Sep 19 '18 at 13:40

2 Answers2

12
  1. work with Ef core LINQ queries directly.

You can get an instance of DbContext using GetDbContext() of IDbContextProvider.

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.

You can disable transactions by applying [UnitOfWork(IsDisabled = true)] attribute

Here is a relevant article on transaction management with ASP.NET Boilerplate.

koryakinp
  • 3,989
  • 6
  • 26
  • 56
  • 1
    You can get an instance of DbContext using GetDbContext() of IDbContextProvider --> How did you get DbContext using GetDbContext() of IDbContextProvider? Do you have any sample code? – ManishKumar May 14 '19 at 06:44
  • 2
    getting exception `System.ArgumentNullException: 'Value cannot be null. Arg_ParamName_Name'` – Nitin Sawant Jun 26 '19 at 04:28
1

@NitinSawant I had a similar issue, though in my case the parameter in question was specifically called out as unitOfWork. I had a database sweep-and-update seed helper class that was run from the Postinitialize method of a module:

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...
}

In this case, it was fortunately just a question of also resolving a unit of work to wrap the other object's construction.

using Abp.Domain.Uow;

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

So @koryakinp's answer gave me most of the solution and I just needed the above adjustment to get things going for my particular use case.

Andrew Hodgkinson
  • 4,379
  • 3
  • 33
  • 43