Ravi
Ravi

Reputation: 1273

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(history1);
 }
 }

Thinks

Upvotes: 0

Views: 2094

Answers (3)

Jason Evans
Jason Evans

Reputation: 29186

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);

Upvotes: 4

Klaus Byskov Pedersen
Klaus Byskov Pedersen

Reputation: 120997

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

Upvotes: 0

Regent
Regent

Reputation: 5602

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();

Upvotes: 0

Related Questions