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

Spring Data MongoDB tries to generate queries for custom repository methods

java mongodb spring-data spring-data-document

Based on the Spring Data Document documentation, I have provided a custom implementation of a repository method. The custom method's name refers to a property which doesn't exist in the domain obje...

loader Animation null pointer?

android

I'm attempting to implement an animated drawable with the following...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.