[英]Basic LINQ for updating a collection property on object
我想知道如何使用LINQ進行此基本操作。 我有一個更新功能,該功能接受一個視圖模型對象,該對象具有一個屬性,該屬性是另一個視圖模型對象的列表,我想遍歷這些對象並更新數據庫。 這是我的代碼:
public void UpdateInspection (EditInspectonViewModel editedInspection)
{
//get the inspection we're editing
Inspection inspection = _repo.GetAll<Inspection>().Single(x=>x.Id==editedInspection.Id;
//set the values to what was passed in
inspection.Name = editedInspection.Name;
inspection.Description = editedInspection.Description;
// Here is where I'm stuck (note-Damages is of type DamageViewModel)
foreach (var damage in editedInspection.Damages)
{
// How do I get a reference to the inspection record's corresponding
// damages records?
}
_repo.SaveChanges();
}
是否有LINQ語法可以讓我更新這些子記錄中的值(即檢查損壞)?
如果我了解您想要的內容,則可以使用Join LINQ方法,如下所示:
public void UpdateInspection (EditInspectonViewModel editedInspection)
{
//get the inspection we're editing
Inspection inspection = _repo.GetAll<Inspection>().Single(x=>x.Id==editedInspection.Id;
//set the values to what was passed in
inspection.Name = editedInspection.Name;
inspection.Description = editedInspection.Description;
// Here is where I'm stuck (note-Damages is of type DamageViewModel)
var damages = editedInspection.Damages
.Join(inspection.Damages,
d => d.Id, d => d.Id,
(vmDmg, dbDmg) => new { vmDmg, dbDmg });
foreach (var damage in damages)
{
damage.dbDmg.Property = damage.vmDmg.Property;
}
_repo.SaveChanges();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.