Returns an empty row using Linq to SQL - Linked table without rows - ASP.Net MVC

I have a 1 to many relationship with the following tables - Person and Email. When using linq to sql and ASP.Net MVC, I would like to show the first email or blank line in the Person view using the following code:

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

In cases where there are no email lines, I get a NullReferenceException. I can return null safe values ​​from SQL using a view or sproc, but I would just like to use common linq for sql objects bound to tables.

+5
source share
3 answers
Model.Emails.Select(x => x.EmailAddress).FirstOrDefault() ?? string.Empty
+8
<%= Html.Encode((Model.Emails.FirstOrDefault() ?? new Email { EmailAddress = string.Empty }).EmailAddress) %>  

, .

+1

:

Model.Emails.Select(z => z.EmailAddress).DefaultIfEmpty("zzz").FirstOrDefault();

I thought you could do it all inside FirstOrDefault, but I was wrong - oh! However, I also forgot that when using DefaultIfEmpty you can just call First ().

Model.Emails.Select(z => z.EmailAddress).DefaultIfEmpty("zzz").First();

Of course, replace ZZZ with just "" (not string.empty, this is optional), but it's nice to see those posts where the explication is selected by default when you write it first.

+1
source

All Articles