小编典典

LINQ to Entities在结果上分割字符串

sql

我有一条LINQ语句,如下所示:

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();

这将失败,因为拆分功能失败,IpAddresses因为LINQ to Entities无法将此查询转换为SQL。

这是有道理的,但是优雅地实现这一目标的等效方法是什么?我想到的唯一方法是在检索到的字符串上手动运行一个循环,然后将其拆分,但我想一次获得它。


阅读 217

收藏
2021-03-23

共1个答案

小编典典

您可以AsEnumerable用来使选择发生在内存中,而不是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()
    });
2021-03-23