LINQ"不在"不工作

时间:2013-07-18 12:46:34

标签: c# linq linq-to-sql

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

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 }

上面的代码中写着“a.id中不包含db.AdminAdjusterStatus.adjusterID的内容。

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

A9EC05B5-651D-4AA7-8275-1F6BFE212C03
1BDE55D9-ED0A-4854-9D5F-B89DB17F02D2

然后,LINQ查询给了我:

A9EC05B5-651D-4AA7-8275-1F6BFE212C03
1BDE55D9-ED0A-4854-9D5F-B89DB17F02D2
e21ff49c-9505-495d-b4a3-c259ee3459d6

然而,它应该只给我:

e21ff49c-9505-495d-b4a3-c259ee3459d6

4 个答案:

答案 0 :(得分:1)

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)

...

答案 1 :(得分:1)

您可以尝试对空记录执行左连接和过滤。没有数据进行测试我无法确定是否可以“开箱即用”,但我已经多次使用以下代码进行这样的过滤:

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相同。

答案 2 :(得分:1)

感谢大家的帮助,对不起浪费任何人的时间。我意识到这一行:

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

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

再次感谢您的帮助!

答案 3 :(得分:1)

也许这可行吗?

            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 };