I have been trying to create a LINQ statement that will join 3 tables with left outer joins. When I try to run the code, I am receiving a 'System.NullReferenceException' error.
var model = from con in dbo.Contacts
from conSpe in dbo.Contact_Specialties
.Where(cs => cs.ContactID == con.ContactID)
.DefaultIfEmpty()
from lan in dbo.Languages
.Where(l => l.ContactID == con.ContactID)
.DefaultIfEmpty()
orderby con.familyName
where (searchFirst == null || con.givenName.StartsWith(searchFirst)) &&
(searchLast == null || con.familyName.StartsWith(searchLast))
select new PhysicianDirectory
{
Contact = con,
Contact_Specialty = conSpe,
Language = lan
};
return View(model);
Below is my code for my Direcory.cs Model in which I want to use the PhysicianDirectory class within my View.
[Table("Contacts")]
public class Contact
{
[Key]
public int ContactID { get; set; }
public string familyName { get; set; }
public string givenName { get; set; }
public string additionalName { get; set; }
public string honorificSuffix { get; set; }
public string title { get; set; }
public string School { get; set; }
}
[Table("Languages")]
public class Language
{
[Key]
public int LanguageID { get; set; }
public int ContactID { get; set; }
public string LanguageSpoken { get; set; }
}
[Table("Contact_Specialties")]
public class Contact_Specialty
{
[Key]
public int ContactID { get; set; }
public int SpecialtyID { get; set; }
public string Specialty1 { get; set; }
public string Specialty2 { get; set; }
}
public class PhysicianDirectory
{
public Contact Contact { get; set; }
public Language Language { get; set; }
public Fellowship Fellowship { get; set; }
public Contact_Specialty Contact_Specialty { get; set; }
}
The 'System.NullReferenceException' error keeps appearing when I try to enter any information from Language class. The Language data will appear if I take out .DefaultIfEmpty() but will only show a small portion that is selected within the Language table. Is there a way for empty space to appear in place of NULL in code so the 'System.NullReferenceException' doesn't appear?
@model IEnumerable<MvcDirectory.Models.PhysicianDirectory>
<div id="DirectoryList">
@foreach (var item in Model)
{
<a href='@Url.Action("Details", "Profile", new { id = item.Contact.ContactID })'>
<div class="PhysicianDetails">
<img src="~/Images/Capture.png" alt="Physician IMG" />
<h4>@item.Contact.givenName @item.Contact.additionalName @item.Contact.familyName, @item.Contact.honorificSuffix</h4>
<p>@item.Contact_Specialty.Specialty1</p>
<p>@item.Contact_Specialty.Specialty2</p>
<p>@item.Contact.title</p>
<p>@item.Language.LanguageSpoken</p>
</div>
</a>
}
</div>
Any suggestions? Thanks!
Just handle item.Language
being null in your view:
<p>@item.Language == null ? "" : @item.Language.LanguageSpoken</p>
In C# 6 this is even simpler:
<p>@item.Language?.LanguageSpoken</p>
(Assuming that null ends up as an empty string in Razor...)
See more on this question at Stackoverflow