Tuesday, 6 June 2017
Difference between singleordefault() and firstordefault() , single() and first() - entity framework
// Entity framework
// Difference between singleordefault() and firstordefault() , single() and first()
/*
* Single and SingleOrDefault
* * Single
It returns a single record if the match found.
An exception is thrown, if none or more than one match found.
* * SingleOrDefault
It returns a single record if match found.
An exception is thrown, if more than one match found. A default value is returned, if no match is found.
*/
/*First
It returns first record from the collection if one or more than one match found.
An exception is thrown, if no match is found.
* FirstOrDefault
It returns first record from the collection if one or more than one match found.
A default value is returned, if no match is found for that element in the collection.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MyMVC.Controllers
{
public class PersonController : Controller
{
//
// GET: /Person/
AdventureConnection connection = new AdventureConnection();
public ActionResult Index()
{
var
firstName = connection.People.Where(m => m.BusinessEntityID ==
99945).Select(m => m.FirstName).SingleOrDefault();
//SELECT TOP (2) [Extent1].[FirstName] AS [FirstName] FROM
[Person].[Person] AS [Extent1] WHERE 15 = [Extent1].[BusinessEntityID]
//if there are multiple rows in the table then
SingleOrDefault and Single throws error. below line thows error
//var FirstName = connection.People.Where(m =>
m.PersonType == "EM").Select(m => m.FirstName).SingleOrDefault();
//var FirstName = connection.People.Where(m =>
m.PersonType == "EM").Select(m => m.FirstName).Single();
//it will select first matching reconrd from database.
this will work if there are more matches. if no record found then it will thorw
"Sequence contains no elements" exception
var
LastName = connection.People.Where(m => m.PersonType == "LEM").Select(m =>
m.FirstName).First();
//SELECT TOP (1) [Extent1].[FirstName] AS [FirstName] FROM
[Person].[Person] AS [Extent1] WHERE N'EM' = [Extent1].[PersonType]
//it will select first matching reconrd from database.
this will work if there are more matches.also work if no record found, return
null if no record found.
var
MiddleName = connection.People.Where(m => m.PersonType == "LEM").Select(m =>
m.MiddleName).FirstOrDefault();
//SELECT TOP (1)
[Extent1].[MiddleName] AS [MiddleName] FROM [Person].[Person] AS
[Extent1] WHERE N'EM' = [Extent1].[PersonType]
ViewBag.firstName = firstName;
return View();
}
}
}
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment