tags:

views:

38

answers:

3

Hi,

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

A: 

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

klausbyskov
No, it won't. `null as History` is just `null`.
Joren
@Joren, you are right. Thanks for catching that.
klausbyskov
+4  A: 

Hi there.

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

Cheers. Jas.

Jason Evans
A: 

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