我正在使用mvvm模式。我可以在运行命令时从项目列表中选择一个viewmodel,我想删除这个项目。
对于这个项目,我有两个repositorys(和一个接口)EquipmentRepository和DummyEquipmentRepository,EquipmentRepository连接到一个数据库,并有一个方法delte(从接口实现),如:
public void DeleteItem(Equipment obj)
{
var db = new AppContext();
db.Equipment.Remove(obj);
db.SaveChanges();
}
但是在我的viewmodel中我选择了equipmentViewModels而不是对象,我应该如何传递所选的Object而不是viewmodel?
我试图在我的viewmodel中运行
myData.DeleteItem(SelectedEquipment);
但这需要一个Equipment对象而不是EquipmentViewModel
答案 0 :(得分:0)
答案很简单明了:创建它。
myData.DeleteItem(new Equipment
{
EquipmentId = SelectedEquipment.EquipmentId
});
或展开您的存储库以按ID删除
public void DeleteItem(Equipment obj)
{
var db = new AppContext();
db.Equipment.Remove(obj);
db.SaveChanges();
}
public void DeleteItemById(int equipmentId)
{
var equipment = new Equipment
{
EquipmentId = equipmentId
};
// this should really be done in the constructor, as you want to keep the context for the lifetime of your repository, which should encompass a unit of work
var db = new AppContext();
db.Equipment.Attach(equipment);
db.Equipment.Remove(equipment);
db.SaveChanges();
}
修改强>
由于您似乎正在使用实体框架,因此上述应该可行。当然,您可以先通过Id获取对象,然后将其传递给DeleteItem
。
替代方式
public void DeleteItemById(int equipmentId)
{
var db = new AppContext();
var equipment = db.Equipment.Where( e => e.EquipmentId == equipmentId);
db.Equipment.Remove(equipment);
db.SaveChanges();
}