Page 1 of 1

get a connection using EF generated classes

Posted: Mon 08 Dec 2014 04:58
by blackfrancis75
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,

Re: get a connection using EF generated classes

Posted: Mon 08 Dec 2014 13:32
by Shalex
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;

Re: get a connection using EF generated classes

Posted: Tue 23 Dec 2014 21:13
by blackfrancis75
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

Re: get a connection using EF generated classes

Posted: Wed 24 Dec 2014 08:44
by Shalex
This is a designed behaviour if your model uses the EntityObject template.