有人可以解释如何从EF结果集中有条件地删除对象吗?
这是我的代码
var newClubKitOrders = from q in db.NewClubKitOrders where q.NewClubId == ncbId select q;
if (newClubKitOrders.Any())
{
foreach (NewClubKitOrder order in newClubKitOrders)
{
if (checkedStatus == true)
{
order.OrderDate = DateTime.Now;
}
else
{
//delete the row (order.delete())
}
}
newClubKitOrders.SaveChanges();
}
由于
答案 0 :(得分:4)
您无法删除' order'在“foreach”循环中。所以试试“for”循环。
答案 1 :(得分:0)
像这样:
else
{
newClubKitOrders.DeleteObject(order);
}
Here is a good SO on some other options and how it all works.
编辑:同样是的,使用for循环,我没有注意到你正在迭代的东西。谢谢Rashmin Javiya!
答案 2 :(得分:0)
尝试以下代码,我已将其他列表中的列表复制为安全的一面。临时列表只是遍历,但实际交易发生在原始列表
var newClubKitOrders = from q in db.NewClubKitOrders where q.NewClubId == ncbId select q;
if (newClubKitOrders.Any())
{
var TempnewClubKitOrders = newClubKitOrders.ToList();
for(int i=0; i< TempnewClubKitOrders.Length; i++)
{
if (checkedStatus == true)
{
newClubKitOrders[i].OrderDate = DateTime.Now;
}
else
{
db.NewClubKitOrde.DeleteObject(newClubKitOrders[i]);
}
}
db.SaveChanges();
}
答案 3 :(得分:0)
这应该有效:
var newClubKitOrders = from q in db.NewClubKitOrders where q.NewClubId == ncbId select q;
if (newClubKitOrders.Any())
{
foreach (NewClubKitOrder order in newClubKitOrders)
{
if (checkedStatus == true)
{
order.OrderDate = DateTime.Now;
}
else
{
db.NewClubKitOrders.Remove(order);
}
}
db.SaveChanges();
}