Reputation: 15955
To reuse open connections, I'm attempting to follow patterns seen in answers such as:
These examples use System.Data.EntityClient.EntityConnection
which I'm unable to locate a reference using Entity Framework Core.
using (var conn = new EntityConnection(connectionString))
{
conn.Open();
using (var db = new MyContext(conn))
{
...
db.SaveChanges()
}
}
Is EntityConnection
not available in EF Core, or is there a package I need to reference beyond the Entity Framework Core packages?
Upvotes: 0
Views: 1173
Reputation: 89406
First, the store connection typically has connection pooling, so the connection isn't actually being opened and closed with each new DbContext.
EF Core doesn't have EntityConnection because it only supports CodeFirst, where the mapping is generated from Attributes/Fluent API/Conventions. EntityConnection is for specifying the mapping from EDMX files.
To open a EF Core DbContext using an existing connection, you can provide the connection in the DbConnectionOptions. To add a constructor that accepts an existing Store Connection would look something like this:
public class Db : DbContext
{
private readonly SqlConnection con;
public Db() {}
public Db(SqlConnection con)
{
this.con = con;
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (con != null)
{
optionsBuilder.UseSqlServer(con);
}
else
{
optionsBuilder.UseSqlServer(@"Server=.;Database=EfCoreTest;Trusted_Connection=True;");
}
}
Upvotes: 2