我的SQL Server数据库中有一个名为product和category的表。产品表包含列category_id来存储映射类别。一种产品可以映射到任意多个类别,例如category_id(1,25,44,11,21),映射ID将作为逗号分隔的字符串存储。

现在,我想使用linq从产品表中检索产品,其中产品包含从下拉菜单中选择的类别。

例如,我想检索产品where category id =1。我的linq查询是

var prodlst = (from p in db.Products
           where (p.PCategory_Id.EndsWith(""+categoryid+"")||
           p.PCategory_Id.Contains("," + categoryid + ",") ||
           p.PCategory_Id.Contains("" + categoryid + ",") ||
           p.PCategory_Id.Contains("," + categoryid + ""))
           select new ProductBO
           {
             Id = p.Id,
             Product_Name = p.Name,
             Price = p.Price
    }).ToList();


它会检索类别ID = 1或11或21的所有值,但我只想在类别ID恰好为1的情况下进行检索

最佳答案

我不确定EntityFramework是否可以翻译这个。如果不尝试,请使其枚举。

db.Products.Where(t=> PCategory_Id.Split(',').Select(int.Parse).Contains(categoryid));

db.Products.AsEnumerable().Where(t=> PCategory_Id.Split(',').Select(int.Parse).Contains(categoryid));

关于c# - 如何在C#中使用linq检查具有给定值的数据库列中存储的逗号分隔值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/43775306/

10-12 17:02
查看更多