使用 LINQ 和 SQLServer 将 int 和字符串与前导零进行比较

Compare int and string with leading zeros with LINQ and SQLServer

上下文

我在数据库中有两个实体,一对多关系如下所示:

public class Material {
    public long MaterialCode { get; set; }
}

public class MaterialDescription {
   [StringLength(18, MinimumLength = 18)]
   public string MaterialCode { get; set; }
}

如何使用 LINQ 查询给定 material 的所有描述?

我尝试了什么?

    var descriptions = ctx.MaterialDescripions
        .Where(d => long.Parse(d.MaterialCode) == material.MaterialCode);

给出错误:LINQ to Entities does not recognize the method Int64 Parse(System.String)

    var descriptions = ctx.MaterialDescriptions
        .Where(d => d.MaterialCode.TrimStart('0') == material.MaterialCode.ToString());

给出错误:System.String TrimStart(char[]) is only supported in LINQ to Entities when there are no trim characters specified as arguments

SQL 服务器(假设这就是您正在使用的)将允许您将前导零的字符串转换为 bigint,因此您可以自己构造 SQL 查询:

var descriptions = ctx.MaterialDescriptions
    .SqlQuery("SELECT * FROM MaterialDescriptions WHERE CAST(MaterialCode AS bigint) = @p0",
              material.MaterialCode);

您可以阅读有关原始 SQL 查询的更多信息 here and here

终于有了解决方案!

感谢Jeff Ogata with his answer

    var descriptions = ctx.MaterialDescriptions
        Where(d => d.MaterialCode.Substring(SqlFunctions.PatIndex("%[^0]%", d.MaterialDescription) == material.MaterialCode.ToString()));