Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/332.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# Linq中字符(字符串)编码的数对数比较_C#_Sql Server_Sql Server 2008_Linq To Sql_Linq To Entities - Fatal编程技术网

C# Linq中字符(字符串)编码的数对数比较

C# Linq中字符(字符串)编码的数对数比较,c#,sql-server,sql-server-2008,linq-to-sql,linq-to-entities,C#,Sql Server,Sql Server 2008,Linq To Sql,Linq To Entities,我有这个疑问 levelnumber = (from b in bv.baLevels where b.ba_Level_Code == ("0" + SqlFunctions.StringConvert((double)cl.Level_Num.Value)) && b.isActive == 1 select (b.ba_Level_Code + " - " + b.ba_Level_Desc)).Fir

我有这个疑问

  levelnumber = (from b in bv.baLevels
                 where b.ba_Level_Code == ("0" + SqlFunctions.StringConvert((double)cl.Level_Num.Value)) && b.isActive == 1
                 select (b.ba_Level_Code + " - " + b.ba_Level_Desc)).FirstOrDefault(),
我的问题是b.ba_级别代码是字符串

cl.Level_Num是Int

baLevels表I有此ba_级别代码值有008

但是cl是这个cl.Level_Num有8个的bacodebrary表

如果我用硬编码的值进行查询

 levelnumber = (from b in bv.baLevels
                where b.ba_Level_Code == "008" && b.isActive == 1
                select (b.ba_Level_Code + " - " + b.ba_Level_Desc)).FirstOrDefault(),
如何显示008?我得到的等级数有8。我需要将该值更改为008


谢谢

您可以使用
string.Format
指定您的'cl.Level_Num'转换为具有最小位数的字符串:

string.Format("{0:D3}", cl.Level_Num.Value) // would ouput "008" value 8
因此:


我看不出有什么好办法可以在LINQ-to-Enties做到这一点。假设您无法修改
ba_Level_code
列的数据类型,我认为您最好的选择是向该表添加一个持久化的表,对其进行索引,然后在查询中使用该列

例如,如果定义了列

ba_Level_Code_Int as (case when isnumeric(ba_Level_Code)= 1 then cast(ba_Level_Code as int) end) persisted
那么您的LINQ查询可以是

levelnumber = (from b in bv.baLevels   
               where b.ba_Level_Code_Int == cl.Level_Num.Value && b.isActive == 1   
               select (b.ba_Level_Code + " - " + b.ba_Level_Desc)).FirstOrDefault();

谢谢Jeffora,但我在表中还有一些其他级别的数字,比如046023056…等等。。我想那一次我会遇到问题。我遇到这个错误。LINQ to Entities无法识别方法“System.String Format(System.String,System.Object)”方法,并且此方法无法转换为存储表达式。@user957178看起来必须将第二个参数强制转换为类型。仅供参考字符串。Format调用在这些情况下也可以工作(就格式而言,-D3表示最少3位,因此如果需要,将在前导零中加上)。至于Linq到实体的问题,这听起来像是一个难以回避的问题,我同意adrift的建议
levelnumber = (from b in bv.baLevels   
               where b.ba_Level_Code_Int == cl.Level_Num.Value && b.isActive == 1   
               select (b.ba_Level_Code + " - " + b.ba_Level_Desc)).FirstOrDefault();