Best way to return result from business layer to presentation layer when using LINQ-to-SQL
- by samsur
I have a business layer that has DTOs that are used in the presentation layer. This application uses entity framework.
Here is an example of a class called RoleDTO:
public class RoleDTO
{
public Guid RoleId { get; set; }
public string RoleName { get; set; }
public string RoleDescription { get; set; }
public int? OrganizationId { get; set; }
}
In the BLL I want to have a method that returns a list of DTO. I would like to know which is the better approach: returning IQueryable or list of DTOs. Although I feel that returning IQueryable is not a good idea because the connection needs to be open. Here are the 2 different methods using the different approaches:
First approach
public class RoleBLL
{
private servicedeskEntities sde;
public RoleBLL()
{
sde = new servicedeskEntities();
}
public IQueryable<RoleDTO> GetAllRoles()
{
IQueryable<RoleDTO> role = from r in sde.Roles
select new RoleDTO()
{
RoleId = r.RoleID,
RoleName = r.RoleName,
RoleDescription = r.RoleDescription,
OrganizationId = r.OrganizationId
};
return role;
}
Note: in the above method the DataContext is a private attribute and set in the constructor, so that the connection stays opened.
Second approach
public static List<RoleDTO> GetAllRoles()
{
List<RoleDTO> roleDTO = new List<RoleDTO>();
using (servicedeskEntities sde = new servicedeskEntities())
{
var roles = from pri in sde.Roles
select new { pri.RoleID, pri.RoleName, pri.RoleDescription };
//Add the role entites to the DTO list and return. This is necessary as anonymous types can be returned acrosss methods
foreach (var item in roles)
{
RoleDTO roleItem = new RoleDTO();
roleItem.RoleId = item.RoleID;
roleItem.RoleDescription = item.RoleDescription;
roleItem.RoleName = item.RoleName;
roleDTO.Add(roleItem);
}
return roleDTO;
}
}
Please let me know, if there is a better approach.