根据条件删除具有多个ID的记录 [英] Delete records with multiple ids based on condition

查看:163
本文介绍了根据条件删除具有多个ID的记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面是我的课:

 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的记录.

Now I want to remove all records/only that record with particular id of same group for some ids.

代码:

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.

最后一种情况的预期输出(标志= true):

Id      Name   Group
6       ttt     3
7       ggg     3

但是我认为我还没有这样做,这是一个正确的方法,并且在查询中有一些改进的地方.

But I think that I haven't done this is a proper way, and there is some source of improvement in the query.

注意: ids []将始终包含来自不同组的ID和来自不同组的最高ID.

Note : ids[] will always contains ids from different group and that too highest ids from different group.

如何针对两种情况(flag = true和false)改进查询?

How can I to improve my query for both the cases(flag=true and false)?

推荐答案

关于

var removeRecs=context.Ads.where(t => ids.contains(t.id))
if(flag)
removeRecs.AddRange(context.Ads.where(t=> removeRecs.Any(r =>t.groupId==r.Id)))
Ads.RemoveRange(removeRecs);

这篇关于根据条件删除具有多个ID的记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆