Set Null if no Results Returned EntityFramework

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();

Answers


I propose:

ViewBag.ManagementSystems = db.Words.Where(w => w.WordBaseID == 1 && w.LanguageID == lang)
                                    .Select(x => x.Text).FirstOrDefault();

Need Your Help

SQL - joining 2 subqueries of total and weekly total

sql mysql subquery left-join

I need to create a report with total sales and sales in the last 7 days for each salesman in a given department. I have a table that lists for each sale the date, amount and ID of the salesman, and

Java EE Web Project and Character Encoding

encoding jdbc java-ee glassfish diacritics

we built a java ee web project and use jdbc for storing our data.