简体   繁体   中英

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 = "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. .

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. This is because there is no equivalent in SQL. You can try to define your own function in database like described here: 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:-

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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