Reputation:
Is there a way to tighten this up so that there is only 1 line in the body?
private int _ProjectGuidToId (Guid guid)
{
ProjectEntity res = _dbt.ProjectEntity
.Where(r => r.ProjectGUID == guid.ToString())
.First();
return res.Id;
}
In other words, how do I return 1 value (Id) from 1 row from the database using LINQ in one line of code?
Thanks.
Upvotes: 0
Views: 113
Reputation: 1529
The first will return the type of the object and no casting is needed (More Details.
Just do this line:
return _dbt.ProjectEntity.Where(r => r.ProjectGUID == guid.ToString()).First().Id;
NOTE: If the query is not guaranteed to return one object an InvalidOperationException could be thrown!
Upvotes: 0
Reputation: 46233
How about something like this?
private int _ProjectGuidToId (Guid guid)
{
return _dbt.ProjectEntity.First(r => r.ProjectGUID == guid.ToString()).Id;
}
Upvotes: 2
Reputation: 8075
use this if you want to force the list must contains one item. if list contains more than one item error may raised:
return _dbt.ProjectEntity.Single(r => r.ProjectGUID == guid.ToString()).Id;
and use this if not matter the length of the list:
return _dbt.ProjectEntity.First(r => r.ProjectGUID == guid.ToString()).Id;
Upvotes: -1
Reputation: 7905
You just need to add the .Id to the end of the first line and return the single line.
I would, however, discourage this. A single unreadable line is in my opinion worse code than two readable lines.
Upvotes: 1
Reputation: 38385
The where clause can be eliminated by using the First's predicate clause:
return _dbt.ProjectEntity.First( r => r.ProjectGUID == guid.ToString() ).Id;
Upvotes: 2