我們正在轉換我們的資料庫訪問權限以使用帶有 EF 的 Azure Identity。我嘗試了各種不同的方法但失敗了,因為 EF 期望創建一個模型并將其傳遞到我無法使用 DBConnection 執行的連接字串中。最后,我找到了一種從 SQLConnection 創建 EntityConnection 的方法,這樣我就可以保留原始連接字串中的所有資訊并根據需要添加元資料。這是我的代碼:
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;
}
當我運行它并到達
EntityConnection entityConnection = new EntityConnection( workspace, sqlConnection );
我收到以下錯誤:
System.ArgumentException: 'MetadataWorkspace must have EdmItemCollection pre-registered.'
不知道此時該做什么,并且非常感謝可以提供的任何見解。
uj5u.com熱心網友回復:
萬一其他人遇到這種情況,這就是我必須做的來解決這個問題。我必須注冊作為作業區一部分的每個單獨的專案集合。
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;
}
uj5u.com熱心網友回復:
https://social.msdn.microsoft.com/Forums/en-US/dd7b1c41-e428-4e29-ab83-448d3f529ba4/creating-an-entity-connection-from-a-sql-connection?forum=adodotnetentityframework 我們可以創建來自 MetaDataWorkspace 的新 EntityConnection,然后我用它來構造具有不同模式的 DbContext
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/414970.html
標籤:
上一篇:無法創建物體框架代碼優先遷移
