繁体   English   中英

使用LINQ-to-Entities将结果从业务层返回到表示层的最佳方法

[英]Best way to return result from business layer to presentation layer when using LINQ-to-Entities

我有一个业务层,该业务层具有在表示层中使用的DTO。 该应用程序使用实体框架。

这是一个名为RoleDTO的类的示例:

public class RoleDTO
{
    public Guid RoleId { get; set; }
    public string RoleName { get; set; }
    public string RoleDescription { get; set; }
    public int? OrganizationId { get; set; } 
}

在BLL中,我希望有一个返回DTO列表的方法。 我想知道哪种方法更好:返回IQueryable或DTO列表。 尽管我觉得返回IQueryable不是一个好主意,因为需要打开连接。 这是使用不同方法的两种不同方法:

第一种方法

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;
    }

注意:在上述方法中,DataContext是一个私有属性,并在构造函数中设置,因此连接保持打开状态。

第二种方法

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;
    }
}

如果有更好的方法,请告诉我。

最好不要将模型对象直接发送到表示层,您可以有一个中间层,在其中将这些DTO对象映射到表示层所需的定制对象。

哪种方法接近您的第二种方法,但不完全相同。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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