Showing posts with label Entity Framework. Show all posts
Showing posts with label Entity Framework. Show all posts

Calling SQL Server inbuilt functions in LINQ

Microsoft introduces a new class 'SqlFunctions', in .NET framework 4, to call the SQL Server inbuilt functions directly in LINQ Queries. It is available in "System.Data.Objects.SqlClient" namespace.

The SqlFunctions class contains methods that expose SQL Server functions to use in LINQ to Entities queries. When you use SqlFunctions methods in LINQ to Entities queries, the corresponding database functions are executed in the database.

Ex: The following example executes a LINQ to Entities query that uses the CharIndex method to return all contacts whose last name starts with "Si"

using (AdventureWorksEntities AWEntities = new AdventureWorksEntities())
{
      // SqlFunctions.CharIndex is executed in the database.
     var contacts = from c in AWEntities.Contacts
                           where SqlFunctions.CharIndex("Si", c.LastName) == 1
                           select c;
     foreach (var contact in contacts)
     {
          Console.WriteLine(contact.LastName);
      }
}

Database functions that perform a calculation on a set of values and return a single value (also known as aggregate database functions) can be directly invoked. Other canonical functions can only be called as part of a LINQ to Entities query. To call an aggregate function directly, you must pass an ObjectQuery to the function.

Ex: Below example calls the aggregate ChecksumAggregate method directly. Note that an ObjectQuery is passed to the function, which allows it to be called without being part of a LINQ to Entities query.

using (AdventureWorksEntities AWEntities = new AdventureWorksEntities())
 {
      // SqlFunctions.ChecksumAggregate is executed in the database.
      decimal? checkSum = SqlFunctions.ChecksumAggregate(
            from o in AWEntities.SalesOrderHeaders
           select o.SalesOrderID);
      Console.WriteLine(checkSum);
 }

Note: To Call the Canonical Functions you need to used the EntityFunctions class.

Ex: The following example executes a LINQ to Entities query that uses the DiffDays method to return all products for which the difference between SellEndDate and SellStartDate is less than 365 days:

using (AdventureWorksEntities AWEntities = new AdventureWorksEntities())
 {
    var products = from p in AWEntities.Products
                 where EntityFunctions.DiffDays(p.SellEndDate, p.SellStartDate) < 365
                  select p;
    foreach (var product in products)
    {
        Console.WriteLine(product.ProductID);
    }
}

For more information about SqlFunctions class, please check the below MSDN links

Adding Parameter dynamically to the Entity Framework query

We can pass the parameters dynamically to a entity framework where clause. Below is the code snippet for passing the parameters dynamically...

//Declare the instances for the Entities and ObjectParameter collection
MTEntities objMT = new MTEntities();
List ob = new List();

//Declare the query holder variable
 string strDyn = "";

//Build the query based on the selected used inputs
if(txtName.text !="")
{
 strDyn += "it.Organization =@Organization";
  //Add the object parameter into the collection
  ob.Add(new ObjectParameter("Organization", txtName.Text));
}

if(txtGuide.Text != "")
{
 strDyn = strDyn.Length == 0 ? strDyn + "And" : strDyn;
 strDyn += "it.CityName= @city";
 ob.Add(New ObjectParameter("city", txtCity.Text));
}

// repeat the above if block for all the parameters you need to pass to the query
if (strDyn.Length > 0)
{
if (strDyn.EndsWith("And"))
strDyn = strDyn.Remove(strDyn.Length, -3);  //Removes the Last 'And'
var query = objMT.MT_tblOrganizations.Where(strDyn, ob.ToArray()).Select(O => new { O.CreatedDate, O.OrganizationID, O.Organization, O.Verticals, O.Offerings, O.WebsiteURL});

//Execute and assign the result to the gridview
MyGridview.DataSource = query;
MyGridview.DataBind();
}