ADO.Net Entity Framework : (五) 從SqlConnection物件建立EntityConnection物件
剛好最近寫的專案有這個需求,
因此把做法寫上來跟大家分享一下,
假設我不想透過ConnectionString直接建立EntityConnection,
還有另一種做法,從已經存在的SqlConnection物件建立EntityConnection物件,
做法如下
////已經存在的SqlConnection
SqlConnection sc;
////建立WorkSpace
MetadataWorkspace workspace = new MetadataWorkspace();
EdmItemCollection edmCollection = new EdmItemCollection("res://*/TestModel.csdl");
workspace.RegisterItemCollection(edmCollection);
StoreItemCollection storeCollection = new StoreItemCollection("res://*/TestModel.ssdl");
workspace.RegisterItemCollection(storeCollection);
StorageMappingItemCollection storageMappingItemCollection = new StorageMappingItemCollection(edmCollection, storeCollection, "res://*/TestModel.msl");
workspace.RegisterItemCollection(storageMappingItemCollection);
////利用剛剛建立的WorkSpace搭配SqlConnection來建立EntityConnection物件
using (TestEntities te = new TestEntities(new EntityConnection(workspace, sc)))
{
var users = te.user.Execute(System.Data.Objects.MergeOption.NoTracking).Select(a => a).ToList();
}
給大家參考一下
參考資料
EntityConnection 建構函式 (MetadataWorkspace, DbConnection)
- 如果您覺得這篇文章有幫助,請您幫忙推薦一下或按上方的"讚"給予支持,非常感激
- 歡迎轉載,但請註明出處
- 文章內容多是自己找資料學習到的心得,如有不詳盡或錯誤的地方,請多多指教,謝謝