Entity Framework Core can't find reference to EntityConnection for connection reuse

.net-core c# entity-framework entity-framework-core

Question

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?

1
0
8/17/2017 7:20:09 PM

Accepted Answer

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;");
            }

        }
2
8/17/2017 9:23:15 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow