0

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 Answer 1

1
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();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.