简体   繁体   English

dapper中如何将map查询结果转为object列表

[英]How to map query result to a list of object in dapper

I have a model class like:我有一个 model class 像:

 public class PageEditDto
 {
    public Guid PageId { get; set; }
    public string? Header { get; set; }
    public string? Content { get; set; }
    public DateTime? StartDate { get; set; }
    public DateTime? EndDate { get; set; }
    public int? PageTypeId { get; set; }
    public int PublishPlaceId { get; set; }
    public List<int>? PublishPlacesList { get; set; }
    public int? SubjectTypeId { get; set; }

    public Guid? ApprovedBy { get; set; }
    public DateTime? ApprovedAt { get; set; }

    public string? PageIconPath { get; set; }
    public int? ReadQuantity { get; set; }
    
    public string? MainImage { get; set; }
    public List<string>? ImageGallery { get; set; }
}

In the result object I have several ImageGallery row connected to the PageId ie, there are multiple records having same pageId returning from the sql. I want to map these to "List<ImageGallery" property in my model class. Is there any efficient way to do it other than creating a loop and match the records having the same PageId etc.在结果 object 中,我有几个 ImageGallery 行连接到 PageId,即,有多个记录具有相同的 pageId 从 sql 返回。我想 map 这些到我的 model class 中的“List<ImageGallery”属性。有任何有效的方法吗?除了创建循环并匹配具有相同 PageId 等的记录之外,还可以这样做。

You can use GroupBy on the results to project your model. Here is an example assuming result is what you get back from the Dapper query, PublishPlace is what you named the column containing the PublishPlacesList values and Image is what you named the column containing the ImageGallery values.您可以在结果上使用GroupBy来投影您的 model。这是一个示例,假设result是您从 Dapper 查询返回的结果, PublishPlace是您命名的包含 PublishPlacesList 值的列, Image是您命名的包含 ImageGallery 的列值。

// group by all of the "flat" properties
var pageEdits = result.GroupBy(p => new
    {
        p.PageId, p.Header, p.Content, p.StartDate, p.Endate, p.PageTypeId,
        p.PublishPlaceId, p.SubjectTypeId, p.ApprovedBy, p.ApprovedAt,
        p.PageIconPath, p.ReadQuantity, p.MainImage
    }).Select(m => new PageEditDto
        {
            PageId = m.Key.PageId,
            Header = m.Key.Header,
            Content = m.Key.Content,
            StartDate = m.Key.StartDate,
            Endate = m.Key.Endate,
            PageTypeId = m.Key.PageTypeId,
            PublishPlaceId = m.Key.PublishPlaceId,
            SubjectTypeId = m.Key.SubjectTypeId,
            ApprovedBy = m.Key.ApprovedBy,
            ApprovedAt = m.Key.ApprovedAt,
            PageIconPath = m.Key.PageIconPath,
            ReadQuantity = m.Key.ReadQuantity,
            MainImage = m.Key.MainImage,
            PublishPlacesList = m.PublishPlace.ToList(),
            ImageGallery = m.Image.ToList()
        }).ToList();

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

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