İsmet Alkan
İsmet Alkan

Reputation: 5447

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

Upvotes: 0

Views: 402

Answers (1)

Dark Falcon
Dark Falcon

Reputation: 44191

I propose:

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

Upvotes: 1

Related Questions