Reputation: 5447
I get a Word from the database and printout its "Text" using ViewBag in my ASP.NET MVC3 EntityFramework project.
ViewBag.ManagementSystems = db.Words.Where(w => w.WordBaseID == 1 && w.LanguageID == lang).FirstOrDefault().Text;
However, if no results are returned, I got null exception and program crashes. What is the simplest and best way of printing nothing if no results are returned?
Solutions I know of:
1- Surround with if's or try-catch blocks
2- Use
var query = "SELECT Text FROM Words WHERE WordBaseID = {0} AND LanguageID = {1}";
ViewBag.ManagementSystems= db.Database.SqlQuery<string>(query, 1, lang).FirstOrDefault();
Upvotes: 0
Views: 402
Reputation: 44191
I propose:
ViewBag.ManagementSystems = db.Words.Where(w => w.WordBaseID == 1 && w.LanguageID == lang)
.Select(x => x.Text).FirstOrDefault();
Upvotes: 1