开发者

LinkQ Exception

I write Linq query for keep on fetching data from database. First loop table don't have record , so throwing exception. After first loop i have record in the database, my

query is working properly. Below i specified my query give some suggestion first loop(no records in table) i have to modify query or query have to change.

Ex:

 forloop(History history in historyList)
 {
 History history1 = (from p in context.History
                                    where p.TransferCode == history.TransferCode
                                    select p).First<History>()
                                    as History;    
 if(history1 == null)
 {
   SaveToDataBase(history);
 }
 else
 {
   UpdateToDataBase(hi开发者_运维百科story1);
 }
 }

Thinks


Try using .FirstOrDefault() in your LINQ query.

History history1 = (from p in context.History
                                    where p.TransferCode == history.TransferCode
                                    select p).FirstOrDefault<History>()
                                    as History; 

If no History item is found, then history1 will be null. EDIT:

This might be cleaner code for you.

History history1 = context.History.FirstOrDefault(h => h.TransferCode == history.TransferCode);


You can use FirstOrDefault extension method. Also LINQ will be able to figure out your result types, so you don't need to do as History or FirstOrDefault<History>:

History history1 = (from h in context.History
                           where h.TransferCode == history.TransferCode
                           select h).FirstOrDefault();


You can use FirstOrDefault instead of First. And drop the as History part. It's unnecessary.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜