get a connection using EF generated classes

Discussion of open issues, suggestions and bugs regarding ADO.NET provider for PostgreSQL
Post Reply
blackfrancis75
Posts: 2
Joined: Mon 08 Dec 2014 04:51

get a connection using EF generated classes

Post by blackfrancis75 » Mon 08 Dec 2014 04:58

I can create a PgSqlConnection as follows:

Code: Select all

   PgSqlConnection pgConnection = new PgSqlConnection();
   pgConnection.Host = "192.168.1.6";
   ...
But instead I'd like to re-use the Connection that is created as part of the Devart Entity Model I generated from my DB (and already has a connection-string defined).
Something like this:

Code: Select all

     using (var context = new iCModel.iCEntities())
     {
         PgSqlConnection pgConnection = (PgSqlConnection)context.Connection;
However, this doesn't work because these types don't cast. Is there a way to get a connection using the generated classes?
Thanks,

Shalex
Devart Team
Posts: 8033
Joined: Thu 14 Aug 2008 12:44

Re: get a connection using EF generated classes

Post by Shalex » Mon 08 Dec 2014 13:32

Depending on the code generation template (Tools > Entity Developer > Model Explorer > the Templates node) used in your model, try the following code:

a) ObjectContext:

Code: Select all

PgSqlConnection pgConnection = (myObjectContext.Connection as System.Data.EntityClient.EntityConnection).StoreConnection;
b) DbContext:

Code: Select all

PgSqlConnection pgConnection = (((IObjectContextAdapter)myDbContext).ObjectContext.Connection as System.Data.EntityClient.EntityConnection).StoreConnection;

blackfrancis75
Posts: 2
Joined: Mon 08 Dec 2014 04:51

Re: get a connection using EF generated classes

Post by blackfrancis75 » Tue 23 Dec 2014 21:13

a) works
b) throws a class cast exception at runtime:
Exception Unable to cast object of type 'iCModel.iCEntities' to type 'System.Data.Entity.Infrastructure.IObjectContextAdapter'.

but I can continue using approach a)

Thanks

Shalex
Devart Team
Posts: 8033
Joined: Thu 14 Aug 2008 12:44

Re: get a connection using EF generated classes

Post by Shalex » Wed 24 Dec 2014 08:44

This is a designed behaviour if your model uses the EntityObject template.

Post Reply