【发布时间】:2017-10-14 02:47:26
【问题描述】:
下面是我的课:
public partial class Ads
{
public int Id { get; set; }
public int RegionId { get; set; }
public string Name { get; set; }
public int Group { get; set; }
}
记录:
Id Name Group
1 abc 1
2 xyz 1
3 lmn 1
4 xxx 2
5 ppp 2
6 ttt 3
7 ggg 3
现在我想删除所有记录/仅删除具有同一组特定 id 的某些 id 的记录。
代码:
public void Delete(int[] ids,bool flag = false)
{
using (var context = new MyEntities())
{
context.Ads.RemoveRange(
context.Ads.Where(t => (flag ?
(context.Ads.Any(x => ids.Contains(x.Id) && x.Group == t.Group)) : false)));
context.SaveChanges();
}
}
我想要做的是如下所示:
If flag is false with ids=3,5 then
I want to delete only records with Id=3,5
Else if flag is true with ids=3,5 then
I want to delete records with Id=3,5 but all other records too of the group to which ids=3,5 belong to.
Here id=3 belongs to group 1 so I want to delete all records of group1 i.e id=1,2 like wise ids=5 belongs to
group 2 so I want to delete all records of group 2 i.e id=4.
最后一种情况的预期输出(flag=true):
Id Name Group
6 ttt 3
7 ggg 3
但我认为我没有这样做是正确的方法,并且查询中有一些改进的来源。
注意: ids[] 将始终包含来自不同组的 id,并且来自不同组的最高 id。
如何改进我对这两种情况(flag=true 和 false)的查询?
【问题讨论】:
-
嗨学习。请回想I provided before 的建议,它是:在提及您自己时,请始终使用大写的“I”。以英语为母语的读者通常会觉得读“i”很烦人,这种轻微的挫败感可能会妨碍您提供帮助。请您记得在下一篇文章中解决这个问题吗?
标签: c# entity-framework linq