dev-resources.site
for different kinds of informations.
Using Existing Database Connection's with Entity Framework Core
Published at
6/4/2020
Categories
efcore
dotnet
entityframework
Author
Ryan Teh Hoon Meng
Entity Framework Core the default ORM that powers many many projects out there. It is great ORM and does its job great.
But some projects use more than one data access libraries. The post will be demonstrating how to use an existing DbConnection
with Entity Framework Core.
The following code was tested with:
- Dotnet Core 3.1
- Entity Framework Core 3.1.2
You could do it...
At Startup.cs
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<MyDbContext>((IServiceProvider serviceProvider, DbContextOptionsBuilder options) => {
DbConnection connection = // Get your database connection here.
options.UseSqlServer(connection);
});
}
At OnConfiguring
public class MyDbContext : DbContext
{
private readonly DbConnection connection;
public MyDbContext(DbContextOptions options, DbConnection connection) : base(options)
{
this.connection = connection;
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
options.UseSqlServer(connection);
}
}
var options = new DbContextOptionsBuilder<BloggingContext>()
.UseSqlServer(new SqlConnection(connectionString))
.Options;
using (var context1 = new BloggingContext(options))
{
using (var transaction = context1.Database.BeginTransaction())
{
using (var context2 = new BloggingContext(options))
{
...
}
}
}
If you hit System.InvalidOperationException: A transaction is already in progress; nested/concurrent transactions aren't supported.
while calling SaveChanges()
, try the following
ctx.Database.UseTransaction((DbTransaction)transaction); // transaction is returned when you called BeginTransaction()
As per stated in the documentation this only works for relational database only.
Articles
5 articles in total
Understanding Linux Shells: Interactive, Non-Interactive, and RC Files
read article
Fixing SSR Rendering Issues with Angular Resolver for Async Pipe Data
read article
How to Set Up Microsoft Office on Linux Mint 21.3: A Comprehensive Guide
read article
Backup and Restore Linux OS with Rsync
read article
Using Existing Database Connection's with Entity Framework Core
currently reading
Featured ones: