I have following three tables
Employee(empid, name)
Role(roleid, name)
EmpRoleMap(mapid, empid,roleid)
In the index view I show the link of employees with edit link with each employee. When user clicks on edit it opens the edit screeen for the selected employee.
For this page to render I am making two calls to database. First is to get the details about selected employee. Seconds is to query the EmpRoleMap table to find out what all roles that employee belongs to.
I want to do the same stuff in single database call, i.e single call would give me the details about the employee and the roleID from EmpRoleMap & RoleName list for the given Employee.
I am using Code First approach with Scaffolding.
How can I do this using EntityFramework? Can we use "Include" clause with LINQ to get the additional data from other tables (here EmpRoleMap,Role).
You have to do a good Entity Model design. I'm going to try to show you an example of what I'm saying, but remember that at this moment I cannot check the code.
public class EmployeeModel
{
[Key]
[ForeignKey("EmployeeRoles")]
public decimal empid { get; set; }
public string name { get; set; }
public virtual List<EmpRoleModel> EmployeeRoles { get; set; }
}
public class RoleModel
{
[Key]
public decimal roleid { get; set; }
public string name { get; set; }
}
public class EmpRoleModel
{
[Key]
[Column(Order = 0)]
[ForeignKey("Employee")]
public decimal empid { get; set; }
[Key]
[Column(Order = 1)]
[ForeignKey("Role")]
public decimal roleid { get; set; }
public virtual EmployeeModel Employee { get; set; }
public virtual RoleModel Role { get; set; }
}
Now you can navigate to employee roles by the EmployeeRoles property.
Please try this code and give me feedback.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments