How to use joins,first or default data retrieval and sorting functionality using LINQ and EF?


While writing LINQ, you may find this code snippet very useful. I have mentioned few examples to clear the syntax. LINQ stands for Language-Integrated Query. It has powerful query capabilities and easy to understand.

Description-
Multiple tables can be joined and data can be retrieved from it using LINQ query.


private yourentityname db = new yourentityname ();

Make sure entity name should be matched with entity name present in config file. At the time of creation of edmx file it gets saved.


var outputResult = (from firobj in db.firsttablename
join secobj in db.secondtablename
on firobj.firstprimarykey equals secobj.secondprimarykey
where firobj.columnname == somevalue
select new
{
firobj.columnname1_in_firsttable,

firobj.columnname2_in_firsttable,

secobj.columnname1_in_secondtable,

secobj.columnname2_in_secondtable

}).ToList();

How to sort resultset using LINQ?

var outputSorted = outputResult.OrderBy(x => x.columnname).ThenByDescending(y => y.columnname);

In above query, Orderby clause is used to sort data in descending order.

How to retrive data which is first or default one using LINQ and entity framework?

Yourtablename obj = db.yourtablename.FirstOrDefault(t => t.columnname == some_variable_or_some_value);

Above query is used only when single data needs to be fetched from tables of database.


Comments

No responses found. Be the first to comment...


  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: