none
Constructing EF 4.1 DbContext using a DbConnection with Database First

    Question

  • I'm trying to use my class that derived from DbContext that was generated using the Database first approach, but there's a wrinkle:  I want to supply an existing DbConnection object, instead of using an EF 4.1 connection string.

    It seems that everywhere I turn, all database first examples are using a connection string. 

    When I pass an existing connection to DbContext(DbConnection conn), the EF assumes that I'm using Code First and raises an exception.  I'd like to use DbContext(DbConnection, DbCompiledModel, Boolean) to construct the DbContext, but I'm having trouble extracting/building the DbCompiled model.

    How can I do this?

    Monday, June 20, 2011 8:41 PM

Answers

  • Hi,

    You can use an existing DbConnection object by passing it to a DbContext constructor. If the connection object is an instance of EntityConnection, then the model specified in the connection will be used in Database/Model First mode. If the object is an instance of some other type—for example, SqlConnection—then the context will use it for Code First mode.

    See the following blog:

    http://blogs.msdn.com/b/adonet/archive/2011/01/27/using-dbcontext-in-ef-feature-ctp5-part-2-connections-and-models.aspx

     

    Thank you,

    Julia


    This posting is provided "AS IS" with no warranties, and confers no rights.
    • Marked as answer by sevzas Tuesday, June 21, 2011 12:54 PM
    Monday, June 20, 2011 11:03 PM
    Moderator

All replies

  • Hi,

    You can use an existing DbConnection object by passing it to a DbContext constructor. If the connection object is an instance of EntityConnection, then the model specified in the connection will be used in Database/Model First mode. If the object is an instance of some other type—for example, SqlConnection—then the context will use it for Code First mode.

    See the following blog:

    http://blogs.msdn.com/b/adonet/archive/2011/01/27/using-dbcontext-in-ef-feature-ctp5-part-2-connections-and-models.aspx

     

    Thank you,

    Julia


    This posting is provided "AS IS" with no warranties, and confers no rights.
    • Marked as answer by sevzas Tuesday, June 21, 2011 12:54 PM
    Monday, June 20, 2011 11:03 PM
    Moderator
  • That works!

    Here is info on creating the MetadataWorkspace object that is necessary to create an EntityConnection

    http://social.msdn.microsoft.com/forums/en-US/adodotnetentityframework/thread/dd7b1c41-e428-4e29-ab83-448d3f529ba4/

    Tuesday, June 21, 2011 12:55 PM