首页 > 解决方案 > .NET Core - EF - 尝试用数字匹配/替换字符串,导致 System.InvalidOperationException

问题描述

我必须在 SQL 中以最小/最大范围匹配邮政编码的记录

挑战在于数据质量很差,一些邮政编码不仅仅是数字

所以我尝试通过丢弃坏的邮政编码甚至只保留数字来匹配“好的邮政编码”

我试过了

它们都在运行时导致错误,这里是代码:

var data = context.Leads.AsQueryable();
data = data.Include(p => p.Company).Include(p => p.Contact);
data = data.Where(p => Regex.IsMatch(p.Company.ZipCode, @"\d"));
data = data.Where(p => Convert.ToInt32(p.Company.ZipCode) >= range.Min);
data = data.Where(p => Convert.ToInt32(p.Company.ZipCode) <= range.Max);

这是错误:

System.InvalidOperationException: The LINQ expression 'DbSet<Lead>
    .Join(
        outer: DbSet<Company>, 
        inner: l => EF.Property<Nullable<int>>(l, "CompanyId"), 
        outerKeySelector: c => EF.Property<Nullable<int>>(c, "Id"), 
        innerKeySelector: (o, i) => new TransparentIdentifier<Lead, Company>(
            Outer = o, 
            Inner = i
        ))
    .Where(l => !(Regex.IsMatch(
        input: l.Inner.ZipCode, 
        pattern: "\d")))' could not be translated. Either rewrite the query in a form that can be translated, or switch to client evaluation explicitly by inserting a call to either AsEnumerable(), AsAsyncEnumerable(), ToList(), or ToListAsync().

我不知道如何解决这个问题。我真的不明白 AsEnumerable()、AsAsyncEnumerable()、ToList() 或 ToListAsync() 在这里有何帮助

我做错了什么?

感谢您的帮助

标签: asp.net-coreentity

解决方案


我尝试了所有可以想象的

各种 linq/ef 技巧,我什至尝试定义一个从未找到的 DBFunction

一旦我有一个直接用 SQL 编写的正在运行的存储过程,我最终得到了一个列表,而不是 IQueryable,所以我回到了#1

最后,我刚刚在我的表中创建了一个新字段:

邮编号码

它包含一个经过过滤的、转换后的邮政编码字符串


推荐阅读