'How To Get Last Inserted Row From Table Using LINQ?

Employee

Empid | EmployeeName
1-------------Ron
2------------John

Department

Depid | DepartmentName | Status| Empid
1---------------Account--------- 1---------1
2---------------HR----------------1---------1
3---------------Finance----------1---------2
4---------------Design-----------1---------2

Here I have two table Employee and Department. One employee can be in different department such as empid = 1 in two department i.e account and hr similarly empid = 2 in two department i.e finance and design .
Now, for example since empid = 1 is inserted in depid = 1 and depid = 2 but I am tryingto get depid = 2 which is last inserted row for empid = 2.Similarly, for empid = 2 last row of department which is depid = 4.
Now, the problem is that my LINQ join doesnot give the required output.
Since i am very much new to Linq, help will be highly appreciated.Thank you

Below is my LINQ Join

 var empDepList = (from D in db.Department.Where(x => x.Status == 1)
                   join E in db.Employee on D.Empid equals E.Empid
                   select new
                   {
                     D.DepartmentName, E.EmployeeName
                   }).ToList();


Solution 1:[1]

If the Employee.Empid is the primary key, a crude way to do this could be as follows:

var empDepList = 
    (from D in db.Department
     join E in db.Employee on D.Empid equals E.Empid
     where D.Status == 1
     orderby E.Empid, D.Depid descending
     select new {
         D.DepartmentName, E.EmployeeName
     }).FirstOrDefault();

Solution 2:[2]

try Code :

You have Used Group by or Subquery Used achieved your result;

var empDepList = (from E in db.Employee                  
               select {
                DepartmentName= db.Department.where(c=>c.status==1 && c.Empid==E.Empid).LastOrDefault()==null?"":db.Department.where(c=>c.status==1 && c.Empid==E.Empid).LastOrDefault().DepartmentName,
                EmployeeName= E.EmployeeName
               }).ToList();

Solution 3:[3]

This works for me: var lastSequence = context.Periods.OrderByDescending(p => p.Id).FirstOrDefault().Sequence; It order the Periods Table by Id descending and take only one record, then I select the column Sequence of my Periods Table, In this case this returns me 11 Periods Table

Solution 4:[4]

context.MyTable.Find(context.MyTable.Max(p => p.Id));

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 tigerswithguitars
Solution 2
Solution 3 marcolauro23
Solution 4 luqman ahmad