2017-02-04 5 views
3

EDMX 모델이있는 어셈블리가 있습니다. 성공적으로 해당 어셈블리 (metadata=res://MyAssembly/MyModel.csdl|res://MyAssembly/MyModel.ssdl|res://MyAssembly/MyModel.msl ...)에 대한 참조가있는 연결 문자열을 생성자에서 지정하는 DbContext을 만들 수 있습니다.이 경우 모든 것이 올바르게 작동합니다.Entity Framework DbContext를 만들 때 기존 모델을 기존 DbConnection에 "연결"하는 방법?

그러나 이제 외부 소스에서 기존 DbConnection뿐 아니라 기존 DbTransaction을 얻는 상황에 직면했습니다. 이 DbConnection에 대한 강력한 형식의 Entity Framework보기를 원합니다. 따라서 연결 문자열 DbContext 생성자를 사용하는 대신 DbConnection을 사용하는 다른 DbContext 생성자를 사용하고 context.Database.UseTransaction()을 사용하여 기존 트랜잭션을 설정합니다.

이 경우 테이블 중 하나에 액세스하자 마자 The entity type MyType is not part of the model for the current context. 오류가 발생합니다. 내 모델이 기존 DbConnection에 '연결'되어 있지 않은 것으로 보입니다.

그래서, 내 질문은 :

  • 어떻게 든 기존 DbConnection 내 EDMX 함유 어셈블리에서 모델을 "연결"할 수 있습니까?
  • DbConnectionDbCompiledModel을 모두 사용하는 DbContext 생성자가 있습니다. 이것은 내가 원하는 것 같다. 기존 EDMX 포함 어셈블리에서 DbCompiledModel을 추출하려면 어떻게합니까?

답변

0

그냥 내 행운은 바로 현상금 : 거의 전체 응답 (마이너스 거래에 대한 부분)을 게시 한 후 답을 발견 here이었다 - 나는도록 SqlConnection 대신 DbConnection을 찾고 생각하지 않았다. 주어진 본질적

, existingDbConnectionexistingDbTransaction :

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