rgvlee/EntityFrameworkCore.Testing

this.AppDbContext.Database.BeginTransaction() always null.

Closed this issue ยท 7 comments

I set up the mock context like this

var options = new DbContextOptionsBuilder<AppDbContext>()
    .UseInMemoryDatabase(databaseName: "AppDbContext")
    .ConfigureWarnings(x => x.Ignore(InMemoryEventId.TransactionIgnoredWarning))
    .Options;

this.DbContext = Create.MockedDbContextFor<AppDbContext>(options);

But the this.AppDbContext.Database.BeginTransaction() return null when I use like this.

using (var transaction = this.AppDbContext.Database.BeginTransaction())
{
    int id = 1;

        var foo = this.AppDbContext.Foo.FirstOrDefault(a => a.Id == id);
        if (foo != null)
        {
            foo.Modified = DateTime.Now;

            this.AppDbContext.Foo.Attach(foo);
            await this.AppDbContext.SaveChangesAsync(modifiedById);

            transaction.Commit();
        }
}

Error on this line transaction.Commit(); because transaction is null.

Can you guide me, how to use the mock DbContext with Transaction?
Or I did something wrong?

Thank you.

I haven't added transaction support to the mock and the in memory provider (which is the default provider for anything not mocked) as I understand it doesn't support it either.
SQLite may support it, there is an example on how to load that provider in the readme.
If that doesn't work we can consider it as an enhancement.

@rgvlee Thank you for your answer!

When I created the InMemory Database (without the mock) and used the transaction by normal, I got a warning like this.

System.InvalidOperationException: Warning as error exception for warning 'InMemoryEventId.TransactionIgnoredWarning': Transactions are not supported by the in-memory store.
And use 

I just add the Ignore(InMemoryEventId.TransactionIgnoredWarning) to Ignore the Warning, and it still works because the transaction not null.

So it would be perfect and I really appreciate it,
if you can enhancement to support.

Thank you.

Version 3.0.3 has just been released with a fix for this issue. If the efcore 2 and efcore 3 versions have the same problem I'll release an update soon.

Thanks for the update.

I test on entity framework core 3.1, it still has the same problem.

No worries, I'll prioritise the efcore 3 release

I have released updates for efcore 2 (1.3.3) and efcore 3 (2.4.3). As I have test coverage over this issue I will close it in a week if there are no further issues.

It works perfectly, thank you.