I have the following database tables:
Employee table -Database name Employee - EmployeeID is the primary key
JobTitleID EmployeeNumber SectionID EmployeeId
9 1234 2 1
2 8976 3 2
4 7654 1 3
I have another table called Job Title --Database name Employee - prmary key JobTitleID
JobTitleID JobTitle
9 CEO
2 Developer
4 Executive
Section Table - Database name Employee- prmary key SectionID
SectionID Section
1 manager
2 IT
3 Branch
Another table called tblEmployee that reside in another database name - Tracking - primary Key EmployeeNumber
EmployeeNumber EmployeeName
1234 TestEmpName1
8976 TestEmpName2
7654 TestEmpName3
I am using database first approach to create the context class. I need this data to populate a table in the Razor view. How can I get the EmployeeName, JobTitle, section in a LINQ query and then populate a List with this data. I tried writing a stored procedure called GetEmployeeData like this:
SELECT JobTitleID, EmployeeNumber, SectionID, JobTitle, section, EmployeeName
FROM Employee e LEFT OUTER JOIN JOBTitle j ON e.JobTitleID = j.JobTitleID
LEFT OUTER JOIN SECTION s ON e.SectionID = s.SectionID
LEFT OUTER JOIN Tracking.dbo.tblEmployee t ON t.EmployeeNumber = e.EmployeeNumber
I need to populate a List with this data and then populate a table in razor view. I can go with LINQ or SQL stored procedure.
I tried doing this, but didn't work because sql query is returning JobTitle, section and emmployeeName in the sql query and that does not exists in Employee Model.
List<Employee> query = await _empContext.Set<Employee>().FromSqlRaw($"EXECUTE dbo.GetEmployeeData").ToListAsync();
I need JobTitle Section EmployeeName in a table in view.
public partial class Employee
{
[Key]
public int EmployeeId{ get; set; }
public int JobTitleId { get; set; }
public string EmployeeNumber { get; set; }
public int? SectionId { get; set; }
public virtual JobTitle? JobTitle { get; set; }
public virtual Section? Section { get; set; }
}
public partial class JobTitle
{
public int JobTitleId { get; set; }
public string JobTitle { get; set; } = null!;
public virtual ICollection<Employee> Employees{ get; set; } = new List<Employee>();
}
public partial class Section
{
public int SectionId { get; set; }
public string Section { get; set; } = null!;
public virtual List<Employee> Employees { get; } = new List<Employee>();
public virtual ICollection<Section> Section { get; } = new List<Section>();
}
This is my partial context class. I cannot post the entire context class because I have some other columns names then can display the company Name:
public partial class EmployeeContext : DbContext
{
public EmployeeContext()
{
}
public EmployeeContext(DbContextOptions<EmployeeContext> options)
: base(options)
{
}
public virtual DbSet<JobTitle> JobTitle { get; set; }
public virtual DbSet<Section> Section { get; set; }
public virtual DbSet<Employee> Employees { get; set; }
}