用于更新对象的集合属性的基本LINQ
本文关键字:LINQ 属性 集合 更新 对象 用于 | 更新日期: 2023-09-27 18:26:06
我想知道如何使用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();
}