繁体   English   中英

如何从C#中的Varbinary(max)Linq to sql query识别Null值?

[英]How to identify a Null value from Varbinary(max) Linq to sql query in C#?

我的目标是执行一个linq to sql查询,如果varbinary(max)字段不为null,它将从varbinary(max)数据库字段返回一个值。 在下面的代码中,x.doc是数据库中的varbinary(max)。

我的代码的基础是这样的:

    var pdfquery = from x in dataContext.Statements
         where x.enccc == card && x.stDate == datetime      
         select x.doc;

                    if (pdfquery.Count() == 1 )
                    {
                        pdffile = pdfquery.FirstOrDefault().ToArray(); 
                    }
                    else
                    {
                     //go to a webservice to get pdffile and write it to the db
                     }

代码块返回空值,因为if语句为true。 传递两个参数后,数据库中的值为空。

我在“ pdfquery.Count()== 1”部分中尝试过:

  • 如果(pdfquery.Any())
  • 如果(pdfquery.FirstOrDefault()!= null)
  • 如果(pdfquery.FirstOrDefault()。toArray()。Length> 0)
  • 所有这些都给了我一个Null值异常。

    我想念什么? 如何确定何时返回空值varbinary(max)的查询,以便我可以采取适当的措施?

    更新(07/17/14):我决定使用try catch处理Null Refernece异常:

         try
                        {
                            var pdfquery = from x in dataContext.Statements
                                           where x.enccc == card && x.stDate == datetime
                                           select x.doc;
    
                            pdffile = pdfquery.SingleOrDefault().ToArray(); //gets the binary data and converts it to a byte array
    
                        }
                        catch(NullReferenceException nux)
                        {
                            logger.LogDebug("No Binary Data Exists for Statement, making  Request ---- ",nux);
                            getStatment(unencArray); 
                            getByteArray(statementxml);  
                            writeByteArrayToDb(unencArray, pdffile); 
    
                        }
    

    我真的不喜欢这样做,因为我希望能够抛出其他异常。 我将尝试将Byte []更改为?Byte [],希望可以正常处理null值。

    只需将其添加到where子句

    var pdfquery = from x in dataContext.CcStatements
                   where x.enccc == card && x.stDate == datetime && x.doc != null      
                   select x.doc;
    

    如果您只期望一个结果,也可以使用SingleOrDefault(与FirstOrDefault相反)。 最后,如果您这样使用Count(),将对Count进行一个不必要的查询,因为该查询将对Count执行一次,对实际数据执行一次。

    暂无
    暂无

    声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

     
    粤ICP备18138465号  © 2020-2024 STACKOOM.COM