Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ to Entities split string on result

I have a LINQ statement as follows:

var playedBanDataList =
    from bannedPlayers in query
    select new PlayerBanData
    {
        Admin = bannedPlayers.Admin,
        BannedUntil = bannedPlayers.BannedUntil,
        IsPermanentBan = bannedPlayers.IsPermanentBan,
        PlayerName = bannedPlayers.PlayerName,
        Reason = bannedPlayers.Reason,
        IpAddresses = bannedPlayers.IpAddresses.Split(new [] {","}, StringSplitOptions.RemoveEmptyEntries).ToList()
    };

    return playedBanDataList.ToList();

This fails because split function fails on IpAddresses as LINQ to Entities cannot translate this query to SQL.

This makes sense, but then what's an equivalent way of accomplishing this elegantly? The only way I've thought of is to manually run a loop on the retrieved string then splitting it, but I'd like to get it in one go.

like image 301
Xiagua Avatar asked Mar 05 '17 00:03

Xiagua


1 Answers

You can use AsEnumerable to make the select occur in memory instead of EF.

var playedBanDataList = query.AsEnumerable()
    .Select(bannedPlayers => new PlayerBanData
    {
        Admin = bannedPlayers.Admin,
        BannedUntil = bannedPlayers.BannedUntil,
        IsPermanentBan = bannedPlayers.IsPermanentBan,
        PlayerName = bannedPlayers.PlayerName,
        Reason = bannedPlayers.Reason,
        IpAddresses = bannedPlayers.IpAddresses.Split(
            new [] {","}, 
            StringSplitOptions.RemoveEmptyEntries).ToList()
    });
like image 157
juharr Avatar answered Sep 29 '22 18:09

juharr