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

时间:2017-03-05 00:35:54

标签: c# sql entity-framework linq orm

我有一个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();

由于LINQ to Entities无法将此查询转换为SQL,因此IpAddresses上的拆分函数失败,因此失败。

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

1 个答案:

答案 0 :(得分:3)

您可以使用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()
    });