Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return empty string using Linq to SQL - Related table with no rows - ASP.Net MVC

I have 1 to many relationship with the following tables - Person and Email. When using linq to sql and ASP.Net MVC, I'd like to show the first email or an empty string in my Person view using code like this:

<%= Html.Encode(Model.Emails.FirstOrDefault().EmailAddress) %>

In cases where there are no email rows, I receive a NullReferenceException. I can return null safe values from SQL by using a view or sproc, but I'd like to just stick with generic linq to sql objects bound to tables.

like image 601
jlnorsworthy Avatar asked Feb 24 '10 22:02

jlnorsworthy


2 Answers

Model.Emails.Select(x => x.EmailAddress).FirstOrDefault() ?? string.Empty
like image 121
Mark Byers Avatar answered Sep 22 '22 08:09

Mark Byers


<%= Html.Encode((Model.Emails.FirstOrDefault() ?? new Email { EmailAddress = string.Empty }).EmailAddress) %>  

Would work, not super clean to read though.

like image 43
Quintin Robinson Avatar answered Sep 20 '22 08:09

Quintin Robinson