How to handle exception raised in linq

后端 未结 2 659
太阳男子
太阳男子 2021-01-20 12:49

gyus! Suppose I have such simple LINQ expression

IEnumerable res =
    from rqResult in MatchesList
    select new StopListMat         


        
相关标签:
2条回答
  • 2021-01-20 13:15

    Use the TryParseExact method to avoid not needed exceptions.
    I don't understand why you can't use the try-catch block? You really think it is not raised? Also you should check your database for the NULL-values:

    MatchDate = Convert.IsDBNull (rqResult.Row["MatchDate"]) ?   
      DateTime.MinValue : 
      DateTime.ParseExact(rqResult.Row["MatchDate"].ToString(),
        "dd.MM.yyyy HH:m:ss", 
        fmtInfo),
    Remark = (string)rqResult.Row["Remark"] ?? String.EmptyString;
    
    0 讨论(0)
  • 2021-01-20 13:33

    Because of deferred execution the query is not executed until you evaluate the query, such as by making use of the .ToList() method. The exception will be thrown at that time only.

    To avoid the problem you need to modify the query. something as below

    IEnumerable<StopListMatchViewModel> res =
        from rqResult in MatchesList
        select new StopListMatchViewModel
        {
            MatchDate = DateTime.ParseExact(
                ((rqResult.Row["MatchDate"]==null) ?
                    rqResult.Row["MatchDate"] : DateTime.MinValue).ToString(), "dd.MM.yyyy HH:m:ss", fmtInfo),
            Remark = rqResult.Row["Remark"].ToString()
        }
    

    Note : DateTime.MinValue is used when the value of rqResult.Row["MatchDate"] is null which used to avoid null

    0 讨论(0)
提交回复
热议问题