用于更新对象集合 属性 的基本 LINQ
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();
}
我想知道如何使用 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();
}