[英]How to store multiple rows in one variable? C# Entity Framework
public static List<TruckWithModel> GetAllTrucks()
{
using (DAD_BaldipContext ctx = new DAD_BaldipContext())
{
var x = ctx.TruckFeatureAssociation
.Include(t => t.Truck)
.Include(tf => tf.Feature)
.Include(tm => tm.Truck.TruckModel)
.Select(it => new TruckWithModel()
{
Colour = it.Truck.Colour,
Size = it.Truck.TruckModel.Size,
RentalPrice = it.Truck.DailyRentalPrice,
Status = it.Truck.Status,
Model = it.Truck.TruckModel.Model,
Rego = it.Truck.RegistrationNumber,
Features = it.Feature.Description
}) ;
return (List<TruckWithModel>)x.ToList();
}
}
此代碼從相關表TruckFeatureAssociation
、 TruckFeature
、 IndividualTruck
和TruckModel
檢索各種屬性值。
我遇到的問題是TruckFeatureAssociation
有多達 5 個條目用於同一輛卡車,該表是IndividualTruck
和TruckFeature
之間的連接表,其中TruckFeature
是各種功能的表。
對於每個TruckFeatureAssociation
, TruckWithModel
創建一個不同的TruckWithModel
對象,即如果有 3 個關聯的特征,則每輛卡車在我調用此函數的數據網格中顯示三行。
我想要它,以便所有功能都可以存儲在一個對象中。
所以在上面的輸出中,我只想要一行,說警報系統,鍍鉻車輪。
這里的問題是您正在查詢功能,但模型反映了卡車...查詢卡車,獲取它的功能,然后讓您的視圖模型 (TruckWithModel) 幫助格式化視圖的數據..
例如:
[Serializable]
public class TruckWithModel
{
public string Colour { get; set; }
public string Size { get; set; }
public decimal RentalPrice { get; set; }
public string Status { get; set; }
public string Model { get; set; }
public List<string> Features { get; set; } = new List<string>();
public string FormattedFeatures
{
get { return string.Join(", ", Features); }
}
}
現在,當您查詢數據時:
var trucks = ctx.Trucks
.Select(t => new TruckWithModel()
{
Colour = t.Colour,
Size = t.TruckModel.Size,
RentalPrice = t.DailyRentalPrice,
Status = t.Status,
Model = t.TruckModel.Model,
Rego = t.RegistrationNumber,
Features = t.Features.Select(f => f.Description).ToList()
}).ToList();
這假設 Truck 有一個特征集合,其中 TruckFeatureAssociation 只是一個映射實體。 如果您的 Truck 的集合基於 TruckFeatureAssociation:
Features = t.Features.Select(f => f.Feature.Description).ToList()
現在,在您想要顯示特征的視圖中,綁定到FormattedFeatures
屬性以獲取每輛卡車的以逗號分隔的特征列表。
請注意,當您通過.Select()
使用 Projection 時,您不需要使用.Include()
來急切加載相關實體。 EF 可以自動計算出加載什么來滿足投影。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.