3

I have an assembly with an EDMX model. I can successfully create a DbContext specifying in the constructor a connection string with a reference to that assembly (metadata=res://MyAssembly/MyModel.csdl|res://MyAssembly/MyModel.ssdl|res://MyAssembly/MyModel.msl ...), and in that case everything works fine.

However, now I'm faced with a situation where I'm getting an existing DbConnection from an external source, as well as an existing DbTransaction. I'd like to have a strongly-typed Entity Framework view over this DbConnection. So, instead of using the connection-string DbContext constructor, I am using a different DbContext constructor that takes a DbConnection (and then using context.Database.UseTransaction() to set the existing transaction).

In this case, as soon as I try accessing one of my tables, I am getting an error, The entity type MyType is not part of the model for the current context. - it seems that my model isn't "attached" to the existing DbConnection.

So, my questions are:

  • Is it possible to somehow "attach" a model from my EDMX-containing assembly to an existing DbConnection?
  • I've noticed there's a DbContext constructor that takes both a DbConnection and a DbCompiledModel. This seems to be exactly what I need. How can I extract a DbCompiledModel from an existing EDMX-containing assembly?
Eugene Osovetsky
  • 6,443
  • 2
  • 38
  • 59

1 Answers1

0

Just my luck, found an answer right after posting a bounty :) Almost the entire answer (minus the part about transactions) was here - I didn't think of searching for SqlConnection instead of DbConnection.

Essentially, given an existingDbConnection and an existingDbTransaction:

var workspace = new MetadataWorkspace(
            new string[] { "res://*/" },
            new Assembly[] { Assembly.Load("My.Assembly.Name")});
            // can use Assembly.GetExecutingAssembly() if in current assembly
var wrappedConnection = new EntityConnection(workspace, existingDbConnection, false);
var context = new DbContext(wrappedConnection, false)
context.Database.UseTransaction(existingDbTransaction);
Community
  • 1
  • 1
Eugene Osovetsky
  • 6,443
  • 2
  • 38
  • 59