Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ single record forms or defaults if no record

Tags:

c#

linq

I am new to LINQ and am liking it so far, however I am trying to load in some forms by requesting a single record (student). If this doesn't exist I want't default values i.e. empty strings false bools...

so I used:

db = new DataClassesDataContext();        
student = db.ss_students.SingleOrDefault(p => p.student_id == studentID);
txtRegNumber.EditValue = student.car_reg_no;

This failed on the assignment of student.car_reg_no. I realised I seem to have mis-understood the SingleOrDefault method and it actually returns null for the student if it can't find a record. I for some reason was thinking it would return the default values for each of the fields such as student.car_reg_no. I think I am still thinkign in database mode.

This is not a problem I can do code like this:

db = new DataClassesDataContext();        
student = db.ss_students.SingleOrDefault(p => p.student_id == studentID);
if (student != null) 
{
        txtRegNumber.Text = student.car_reg_no;
        //assign more control values
}

And the defaults could either be assigned to the controls in an else or assigned direct on the form.

But is this the right way to do it or am I missing something?

EDIT Thanks for the posts so far I have started the approach suggested by Marc Gravell. I have now got a bit further.

I am now trying to save the data back to the database how would I know if I am updating or inserting a record. Should I be adding bools to record this myself or is their a built in way.

like image 691
PeteT Avatar asked Sep 06 '25 08:09

PeteT


1 Answers

SingleOrDefault returns the default value for the returned type. Which is

  • null for classes/interfaces/delegates
  • 0/false for value types
    • except for Nullable<T>, where it is null

For classes, you get null - this is mainly a way to check "did it exist?". Just create the actual default yourself... perhaps:

YourType x = query.SingleOrDefault() ?? new YourType();

This "null coalescing" approach only executes the right-hand-side (new ...) if the left-hand-side is null. Or more simply:

YourType x = query.SingleOrDefault();
if(x==null) { // use a default
    x = new YourType();
}
like image 57
Marc Gravell Avatar answered Sep 08 '25 18:09

Marc Gravell