views:

113

answers:

1

I'm look at learning a bit more ASP.Net MVC and Linq To Entity.

I'm working on a project using this and am having a problem with the following line of code

ViewData["ProjectName"] = db.Projects.FirstOrDefault(p => p.ProjectId  == task.ProjectId).ProjectName;

It works fine when the record exists but if no record exist it errors because I am trying to examine the ProjectName property of a null object. I realise I could cast the object to a variable and test if its null before storing the ProjectName into the ViewData but am just wondering if there is a neater way of doing this?

I know its a simple question and I could just work around it but if there is a better way of doing this it would be good to know.

Thanks

Gavin

+1  A: 
var project = db.Projects.FirstOrDefault(p => p.ProjectId == task.ProjectId);
if (project != null)
{
  ViewData["ProjectName"] = project.ProjectName;
}
else
{
  //........
}

No cast needed.

Or skip the condition altogether and do this:

ViewData["ProjectName"] = db.Projects.Where(p => p.ProjectId == task.ProjectId)
                           .Select(p => p.ProjectName).FirstOrDefault();
AZ