有效地在模型之间映射

时间:2019-07-02 20:47:53

标签: c# linq asp.net-core

我对asp.net内核有点陌生。在此查询中,它将继续重新查询每个节点上的db以从OrgStructures映射到ToOrgStructureModel的映射,是否有一种方法可以提高效率:

这是它继续查询数据库的地方:.Select(org => org.ToOrgStructureModel(db.OrgStructures.Where(s => s.ParentNodeId == org.NodeId).Count() > 0))

整个查询:

public virtual IList<OrgStructureModel> GetAll()
{

    using (var db = _context)
    {
        var result = db.OrgStructures
                .Where(e => e.FiscalYear == 19)
                .Select(org => org.ToOrgStructureModel(db.OrgStructures.Where(s => s.ParentNodeId == org.NodeId).Count() > 0))
                .ToList();

        _session.SetObjectAsJson("OrgStructure", result);

        return result;
    }
}

ToOrgStructureModel:

public static OrgStructureModel ToOrgStructureModel(this OrgStructure org, bool hasChildren)
{
    return new OrgStructureModel
    {
        NodeId = org.NodeId,
        ParentNodeId = org.ParentNodeId,
        Name = org.Name,
        DepartmentCode = org.DepartmentCode,
        Acronym = org.Acronym,
        LegacyId = org.LegacyId,
        hasChildren = hasChildren
    };
}

OrgStructureModel:

public class OrgStructureModel
    {
        [ScaffoldColumn(false)]
        public int? NodeId { get; set; }

        [Required]
        public string Name { get; set; }

        public string Acronym { get; set; }

        public string DepartmentCode { get; set; }

        public int? ParentNodeId { get; set; }

        public int? LegacyId { get; set; }

        public int FiscalYear { get; set; }

        public int DepartmentId { get; set; }


    [ScaffoldColumn(false)]
        public bool hasChildren { get; set; }
        public OrgStructure ToEntity()
        {
            return new OrgStructure
            {
                NodeId = NodeId,
                Name = Name,
                Acronym = Acronym,
                ParentNodeId = ParentNodeId,
                DepartmentCode = DepartmentCode,
                LegacyId = LegacyId,
                FiscalYear = FiscalYear,
                DepartmentId = DepartmentId
            };
        }
    }

2 个答案:

答案 0 :(得分:2)

在使用Linq-to-sql时避免使用自定义方法。

这是一种不使用count(pedGoTo.getPeds(),p->rectangularArea.contains(p.getX(),p.getY())); 方法的可行替代方法:

ToOrgStructureModel

答案 1 :(得分:2)

您正在创建许多查询,实质上是针对将要拉出的每条记录,它将查询一次以上的时间来检查它们中的每条hasChildren

在主模型中包含指向子项的链接(如果是集合,则使其成为集合),

public class OrgStructureModel
{
    ...
    public int? ChildId {get;set;}
    public OrgStructureModel Child {get;set;}
}

然后您可以在查询中创建支票

     var result = db.OrgStructures
            .Where(e => e.FiscalYear == 19 && e.ChildId != null)
            .Select(org => org.ToOrgStructureModel())
            .ToList();

还请阅读this关于投影的博客文章。