We are converting our DB access to use Azure Identity with EF. I tried various different methods and failed because EF is expecting a model to be created and passed into the connection string which i was unable to do with DBConnection. Finally I found a way to create the EntityConnection from a SQLConnection so I can retain all the information from the original connection string and add the metadata as needed. Here's my code:
public static EntityConnection GetEntityConnectionString( string efConnectionString, string accessToken )
{
MetadataWorkspace workspace = new MetadataWorkspace( new string[] { "res://*/" }, new Assembly[] { Assembly.GetExecutingAssembly() } );
SqlConnection sqlConnection = new SqlConnection( efConnectionString );
sqlConnection.AccessToken = accessToken;
EntityConnection entityConnection = new EntityConnection( workspace, sqlConnection );
return entityConnection;
}
When I run this and get to the
EntityConnection entityConnection = new EntityConnection( workspace, sqlConnection );
I get the following error:
System.ArgumentException: 'MetadataWorkspace must have EdmItemCollection pre-registered.'
Not sure what to do at this point and would really appreciate any insight that can be provided.
CodePudding user response:
In case anyone else runs into this, here's what I had to do to resolve the issue. I had to Register each individual Item Collection that is a part of the workspace.
public static EntityConnection GetEntityConnectionString( string efConnectionString, string accessToken )
{
MetadataWorkspace workspace = new MetadataWorkspace( new string[] { metadata[0] }, new Assembly[] { Assembly.GetExecutingAssembly() } );
var edmItemCollection = new EdmItemCollection( "res://*/<filename>.csdl" );
var store = new StoreItemCollection( "res://*/<filename>.ssdl" );
var mapping = new StorageMappingItemCollection( edmItemCollection, store, "res://*/<filename>.msl" );
workspace.RegisterItemCollection( edmItemCollection );
workspace.RegisterItemCollection( store );
workspace.RegisterItemCollection( mapping );
SqlConnection sqlConnection = new SqlConnection( efConnectionString );
sqlConnection.AccessToken = accessToken;
EntityConnection entityConnection = new EntityConnection( workspace, sqlConnection );
return entityConnection;
}
CodePudding user response:
https://social.msdn.microsoft.com/Forums/en-US/dd7b1c41-e428-4e29-ab83-448d3f529ba4/creating-an-entity-connection-from-a-sql-connection?forum=adodotnetentityframework we can create a new EntityConnection from a MetaDataWorkspace that I then use to construct a DbContext with a different schema