Reputation: 980
Following line throw exception if there is no matching record
found.
Guid stuId= context.Students.FirstOrDefault(x => x.Name == student.Name).Id;
I understand, i can handle above line
var stuId= context.Students.FirstOrDefault(x => x.Name == student.Name);
if (stuId){}else{}
But,
Can i make the same line more smarter to handle no sequence found error
Guid stuId= context.Students.FirstOrDefault(x => x.Name == student.Name).Id;
Upvotes: 0
Views: 411
Reputation: 460208
Yes, with the null-propagation/conditional operator(new in C#6):
Guid? stuId = context.Students.FirstOrDefault(x => x.Name == student.Name)?.Id;
Now you have a nullable and it's easy to check if there is an id or not:
if(stuId.HasValue)
{
// ...
}
If you can't use C#6 as commented:
Guid stuId = context.Students
.Where(x => x.Name == student.Name)
.Select(x=> x.Id)
.DefaultIfEmpty(Guid.Empty)
.First();
Now you can check against Guid.Empty
:
if(stuId != Guid.Empty)
{
}
If Guid.Empty
is a valid value you could also use a Guid?
here:
Guid? stuId = context.Students
.Where(x => x.Name == student.Name)
.Select(x=> (Guid?) x.Id)
.DefaultIfEmpty(null)
.First();
Upvotes: 2
Reputation: 1130
If you want a solution working in lower version of C# than 6 (not using null-conditional operator), you can use cast operator like this:
var stuId = context.Students.Where(x => x.Name == student.Name).Select(i => (Guid?)i.Id).FirstOrDefault();
This will correctly return null
if no record is found, as null
is a default value for nullable struct
s.
Upvotes: 0
Reputation: 34509
I think you should be able to use the new Null Conditional Operater like so:
Guid? stuId= context.Students.FirstOrDefault(x => x.Name == student.Name)?.Id;
You can read about this new syntax in C#6 on MSDN. Basically in addition the additional question mark, it will check that the statement before isn't null before executing the right hand side. If it is it'll return a null value so you need to make your Guid nullable.
Upvotes: 3
Reputation: 379
You could do it like this:
Guid? stuId = context.Students.FirstOrDefault(x => x.Name == student.Name)?.Id;
if ( stuId.HasValue )
{
// do something if we have a value
}
Which is using the null conditional operator, but you still need to check if you actually got a value before trying to use the value
Upvotes: 0