LINQ”;不在“;不起作用

本文关键字:不起作用 不在 LINQ | 更新日期: 2023-09-27 18:23:57

我正在尝试排除db.AdminAdjusterStatus中存在的具有a.id的项。

from u in db.Users
join a in db.Adjusters on u.id equals a.userID
where u.userType.ToLower() == "adjuster"
   && !(from x in db.AdminAdjusterStatus select x.adjusterID).Contains(a.id)
select new AdjusterProfileStatusItem { user = u, adjuster = a }

上面的代码说,"其中NOT包含db.AdminAdjusterStatus.adjusterID中的a.id

问题是,它不起作用。我在db.AdminAdjusterStatus:中有这两个条目

A9EC05B5-651D-4AA7-8275-1F6BFE212C031第55d9版0a-4854-9D5F-B89DB17F02D2

而且,LINQ查询给了我:

A9EC05B5-651D-4AA7-8275-1F6BFE212C031第55d9版0a-4854-9D5F-B89DB17F02D2e21f49c-9505-495d-b4a3-259ee3459d6

然而,它应该只给我:

e21f49c-9505-495d-b4a3-259ee3459d6

LINQ”;不在“;不起作用

var query = from u in db.Users
             from a in db.Adjusters                         
             where u.userType.ToLower() == "adjuster" && 
             u.id == a.userID && 
             !db.AdminAdjusterStatus.Any(i => i.adjusterID == a.id)

您可以尝试执行左联接并过滤空记录。如果没有数据进行测试,我无法确定它是否会"开箱即用",但我已经多次使用以下代码进行这样的过滤:

db.Users.Join(db.Abjusters, outer => outer.id, inner => inner.userID, new { User = outer, Adjuster = inner })
    .GroupJoin(DBConcurrencyException.AdminAdjusterStatus, outer => outer.Adjuster.id, inner => inner.adjusterID, new { User = outer.User, Adjuster = outer.Adjuster, Admins = inner })
    .SelectMany(grp => grp.Admins.DefaultIfEmpty(), (grp, admin) => new { User = grp.User, Adjuster = grp.Adjuster, Admin = admin })
    .Where(item => item.User.userType == "adjuster" && item.Admin == null)
    .Select(item => new AdjusterProfileStatusItem { user = item.User, adjuster = item.Adjuster });

GroupJoin/SelectMany组合执行左联接,然后您可以过滤对象为空的地方,这应该会产生与NOT IN相同的结果。

感谢大家的帮助,很抱歉浪费了大家的时间。我意识到这条线:

obj.adjusterID = '@(Url.RequestContext.RouteData.Values["id"])';

在我的代码的其他地方,发送的是u.id,而不是我认为的a.id。因此,我在数据库中保存了错误的ID,从而导致了我遇到的问题。

再次感谢您的帮助!

也许这可行?

            var AdjusterItems = from aa in AdminAdjusterStatus
                            join a in Adjusters
                            on aa.AdjusterId equals a.AdjusterId
                            select a.UserId;
        var UsersNotAdjustAdmin = from u in Users
                                  where !AdjusterItems.Any(x => x == u.Id)
                                  && u.UserType.Equals("Adjuster", StringComparison.InvariantCultureIgnoreCase)
                                  select u;
        var result = from u in UsersNotAdjustAdmin
                     join a in Adjusters
                     on u.Id equals a.UserId
                     select new AdjusterProfileStatusItem() { Adjuster = a, User = u };