简体   繁体   中英

LINQ to SQL Query Across Entity Sets Optimization

I have two different databases. One that stores an employee list , and another that stores role/permission information . I'm trying to get used to writing linq queries and this is what I came up with to get a list of employee's that are in a role.

I'm pretty sure there is no way to avoid making two different database calls for this info since they are in different databases, but I think the first two lines of my function calling out to the appSecModel could be created more efficiently. My understanding is that once I call .SingleOrDefault() on the first line, it executes against the database. Then the next line it executes again when I call .ToList() on it.

Is there a way to write these two statements as one so I can only hit the database once for this info?

Note that our permission/role database contains permissions/roles for several different applications built in-house which is why you pass in a programId to avoid role name conflicts.

private static EmployeeDirectoryEntities empModel = new EmployeeDirectoryEntities();
private static ApplicationSecurityEntities appSecModel = new ApplicationSecurityEntities();

public static List<Employee> EmployeesInRole(int programId, string roleName)
{
    var role = (from r in appSecModel.Roles where r.program_id == programId && r.name == roleName select r).SingleOrDefault();
    var roleEmpIds = (from re in appSecModel.EmployeeRoles where re.role_id == role.id select re.employee_id).ToList();
    return (from e in empModel.Employees where roleEmpIds.Contains(e.id) select e).ToList();
}

Make sure you clean your instances and resources you better to use something like this Also using one instance can only be modified if you have one db or some how combine two or add another one two your model.

dynamic role=null;
List<int?> roleEmpIds=null;

 using(ApplicationSecurityEntities appSecModel = new ApplicationSecurityEntities())
{
  role = (from r in appSecModel.Roles where r.program_id == programId && r.name ==  roleName select r).SingleOrDefault();
roleEmpIds = (from re in appSecModel.EmployeeRoles where re.role_id == role.id select  re.employee_id).ToList();

}
using(EmployeeDirectoryEntities empModel = new EmployeeDirectoryEntities())
{

return (from e in empModel.Employees where roleEmpIds.Contains(e.id) select e).ToList();

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM