简体   繁体   English

使用Linq / Lambda在CSV列上使用String.Split()。Contains()

[英]Using String.Split().Contains() on CSV column using Linq/Lambda

I have a database table column that contains a comma separated list of strings. 我有一个数据库表列,其中包含用逗号分隔的字符串列表。 I need to query this table for a string within the comma separated column. 我需要在此表中查询以逗号分隔的列中的字符串。

The table: 桌子:

public class MyObject
{
    public string sIds { get; set; }

    ...
}

If the sIds column in my table contains: 如果我表中的sIds列包含:

sIds = "DG,VO,XX,AB"

and I execute the following code: 然后执行以下代码:

string _sId = "AB";

List<MyObject> designParams = _context.DesignParams
    .AsNoTracking()
    .Where(c => c.sIds.Split(',').Contains(_sId))
    .Select(c => c)
    .ToList();

I get NotSupportedException: LINQ to Entities does not recognize the method 'System.String[] Split(Char[])' method, and this method cannot be translated into a store expression. 我收到NotSupportedException: LINQ to Entities does not recognize the method 'System.String[] Split(Char[])' method, and this method cannot be translated into a store expression. .

There's a lot of articles similar to my issue, but I haven't been able to find an exact solution. 有很多与我的问题相似的文章,但我一直无法找到确切的解决方案。 Is there something wrong with my code or is there a different way this should be done? 我的代码是否有问题,或者应该以其他方式完成?

String.Split is not supported by EF. EF不支持String.Split。 This is because there is no equivalent in SQL. 这是因为SQL中没有等效项。 You can try to define your own function in database like described here: http://sqlperformance.com/2012/07/t-sql-queries/split-strings . 您可以尝试在数据库中定义自己的函数,如此处所述: http : //sqlperformance.com/2012/07/t-sql-queries/split-strings Or you can try move part of logic from server to client. 或者,您可以尝试将部分逻辑从服务器移至客户端。

The equivalent in SQL is "IN", the Contains in LINQ is a bit like reverse:- SQL中的等效项是“ IN”,LINQ中的Contains有点像反向:-

List<MyObject> designParams = _context.DesignParams
.AsNoTracking()
.Where(c => _sId.Contains(c.sIds))
.Select(c => c)
.ToList();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM