我想知道如何使用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语法允许我更新这些子记录中的值(即检查损坏)?
答案 0 :(得分:0)
如果我理解你想要的东西,你可以使用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();
}