Olaitan Adeboye
Olaitan Adeboye

Reputation: 172

Write Join Query in ASP.NET MVC using LINQ

I just finished reading Adam Freeman's Pro ASP.NET MVC book as an introduction to ASP.NET MVC.

However, I ran into a situation where I have to join multiple tables but with Freeman's Method, I am unable to.

Please See my Code Below

EFEmployeeRepository.cs (In My Concrete Folder)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using HRMS.Domain.Abstract;
using HRMS.Domain.Entities;



namespace HRMS.Domain.Concrete
{
    public class EFEmployeeRepository : IEmployeesRepository
    {
        private EFDbContext context = new EFDbContext();           

        public Employee getEmployeeByID(int User_ID)
        {

            // I want to Join the Employee Table with the User Table to Get Employee Details

            Employee employee = context.Employees.FirstOrDefault(p => p.User_ID == User_ID);

            return employee;

        }
    }
}

IEmployeesRepository.cs (Absctract Folder)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using HRMS.Domain.Entities;


namespace HRMS.Domain.Abstract
{
    public interface IEmployeesRepository
    {

        //Get employee Details
        Employee getEmployeeByID (int User_ID);

    }
}

I will need to Join the Employee model with the user Model for a particular Employee and return the data to a controller

Upvotes: 0

Views: 6420

Answers (1)

Adrita Sharma
Adrita Sharma

Reputation: 22213

 var empDetails = (from emp in Context.Employees
             join us in Context.User on emp.User_ID equals us.User_ID
             where emp.User_ID == User_ID
             select new UserDataModel
             {
               User_ID=us.User_ID,
               UserName=us.username,
               EmployeeId=emp.EmployeeId
             }).FirstOrDefault()

Your Data Model :

public class UserDataModel
{
  public int User_ID {get; set;}
  public String UserName {get; set;}
  public int EmployeeId {get; set;}
}

Upvotes: 5

Related Questions