如何将含NOT IN子句的SQL查询转换为Linq语句?
Fixing the LINQ
NOT IN Logic for Your Query Got it, let's clean up that LINQ code to properly match your original SQL's NOT IN clause. Instead of chaining a bunch of && x.Keyword != ... checks, we can use a collection and the negation of Contains()—it's cleaner, more maintainable, and directly maps to the SQL logic you want.
Here's the complete, working code:
public static IEnumerable<SelectListItem> GetProductName() { // Create a list of excluded keywords (matches the NOT IN values from your SQL) var excludedKeywords = new List<string> { "ATRF", "CAST", "EVAL", "FTBS", "KYCB", "RCAN", "RDPT", "REGA", "REGC" }; using (WALLET_CORE_UATEntities _ent = new WALLET_CORE_UATEntities()) { return _ent.SW_TBL_KEYWORD // Filter by scope AND exclude the specified keywords .Where(x => x.Keyword_Scope == "A" && !excludedKeywords.Contains(x.Keyword)) // Map each matching record to a SelectListItem .Select(x => new SelectListItem { Text = x.Keyword, Value = x.Keyword // Use this if you want value and text to be the same; adjust if needed }) // Materialize the query to avoid issues with the disposed context .ToList(); } }
Key Notes:
NOT INEquivalent: The!excludedKeywords.Contains(x.Keyword)is LINQ's way of writingkeyword NOT IN (...)—it tells EF to generate the sameNOT INSQL clause under the hood.- Maintainability: Storing excluded keywords in a list makes it easy to add/remove values later without messing with the query logic.
- Context Disposal: Calling
.ToList()ensures the query runs immediately inside theusingblock. If you skip this, the query would try to execute later when the context is already disposed, causing an error. - Explicit Mapping: Using
.Select()to createSelectListItemmakes your intent clear, instead of relying onSelectListto guess which properties to use.
内容的提问来源于stack exchange,提问作者Aayush Rajopadhyaya
相关产品推荐
相关产品推荐

