### C# - LINQ to Entities 查詢中無法建構實體或複雜類型

• 2073
• 0
• C#
• 2020-07-27

LINQ to Entities 查詢中無法建構實體或複雜類型

var data = db.Store.select(x=> {

x.StoreId,
x.StoreName

}).ToList();

List<Store> list = new List<Store>();

list = db.Store.select(x=> new Store{

Store.Id = x.StoreId,
Store.Name = x.Store.Name
}).ToList();

LINQ to Entities 查詢中無法建構實體或複雜類型

Well, mapped entities in EF basically represent database tables. If you project onto a mapped entity, what you basically do is partially load an entity, which is not a valid state. EF won't have any clue how to e.g. handle an update of such an entity in the future (the default behaviour would be probably overwriting the non-loaded fields with nulls or whatever you'll have in your object). This would be a dangerous operation, since you would risk losing some of your data in the DB, therefore it is not allowed to partially load entities (or project onto mapped entities) in EF

1. 利用匿名類別將資料從資料庫讀取並轉換為LIST，接著再下一次Select，將LIST當中的內容讀出並且轉換為強型別
2. 利用ViewModel將內容讀取出來

List<Store> list = new List<Store>();

list = db.Store.select(x=> new {

x.StoreId,
x.StoreName
}).ToList().select(x => new Store {

StoreId = x.StoreId,
StoreName = x.StoreName,
}).ToList();

List<StoreViewModel> list = new List<StoreViewModel>();

list = db.Store.select(x=> new StoreViewModel{

StoreId = x.StoreId,
StoreName = x.StoreName,
}).ToList();

http://www.zhenghui.idv.tw/