c# - Entity Framework 不支持 x.ToString()!

标签 c# .net entity-framework linq-to-entities

Entity Framework 无法识别我将路由对象转换为特定字符串的 ToString 方法:

public IEnumerable<Route> GetRoutes(string prefix, string searchPattern, string code)
{
    return Routes.
        Where(x => code == null || x.Code == code).
        Where(x => searchPattern == null || x.ToString().Contains(searchPattern)).
        Where(x => prefix == null || x.ToString().StartsWith(prefix));
}

这是我的路线实体:

 public class Route : IDataEntity, ISoftDeletable
    {
        public virtual long Id { get; set; }
        public virtual string Code { get; set; }
        public virtual bool IsDeleted { get; set; }
        public virtual Guid CompanyId { get; set; }
        public virtual IList<LocationInRoute> Locations { get; set; }

        public override string ToString()
        {
            StringBuilder str = new StringBuilder();
            foreach (LocationInRoute loc in Locations)
            {
                if (str.Length > 0)
                {
                    str.Append(" > ");
                }
                str.Append(loc.ToString());
            }
            return str.ToString();
        }
    }

所有的 x.ToString() 都抛出一个 not supported in linq to entities 的异常。 任何解决方法?

最佳答案

您不能在客户端执行此操作 (ToString)。

您必须创建将进行评估的 SQL 函数 - 它可以只对您的位置进行字符串连接(我相信它是相关实体),或者您可以在自定义函数中进行整个测试。然后您可以将该函数导入您的实体模型 (EDMX) 并创建 EdmFunctionAttribute 来调用它 - MSDN

关于c# - Entity Framework 不支持 x.ToString()!,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6213037/

相关文章:

file - 如何在.NET 中重命名文件?

c# - 通过 Entity Framework 中的变量引用表

c# - 如何在 Entity Framework 6 中延迟加载关系?

c# - 在 Visual Studio 2013 中创建新 Git 项目时出错

.net - IDisposable 对象是否意味着只创建和处理一次?

c# - LIKE 比较 Entity Framework 中的列表

sql-server - PM scaffold-dbcontext 未创建主键

c# - 如何找到n位数字的最小值?

c# - 关联范围内的日志消息

.net - 为什么.NET 不允许跨线程操作?