gpt4 book ai didi

Automapper map 自定义集合

转载 作者:行者123 更新时间:2023-12-04 18:13:30 24 4
gpt4 key购买 nike

你好。 我有一个看起来像这样的列表:

public class PagedList<T> : List<T>
{
public PagedList(IEnumerable<T> collection) : base(collection)
{ }
public int TotalItems { get; set; }
public int CurrentPage { get; set; }
public int PageSize { get; set; }
//some other properties
}

并在存储库中用于分页
 public PagedList<TEntity> GetPaged(int page)
{
var pagedEntities = some_query;
return pagedEntities.AsPagedList(totalResults, page, pageSize);
}

在 asp mvc View 模型中也使用相同的 PagedList 进行分页。
是否可以使用 Automapper 和 TotalItems/CurrentPage/... 的所有属性来映射此集合?
   PagedList<DbItem> dbItems = _repository.GetPages(page);
var viewItems = new PagedList<SomeItemView>();
Mapper.Map(dbItems , viewItems);

谢谢你!

最佳答案

这对我有用。你在寻找更通用的东西吗?

public class DbItem
{
public int Id { get; set; }
public string Name { get; set; }
}

public class ViewItem
{
public int Id { get; set; }
public string Name { get; set; }
}

public class PagedList<T>: List<T>
{
public int TotalItems { get; set; }
public int CurrentPage { get; set; }
public int PageSize { get; set; }
}

class Program
{
static void Main(string[] args)
{
MapItems();
}

public static void MapItems()
{
Mapper.CreateMap<DbItem, ViewItem>();
Mapper.CreateMap<PagedList<DbItem>, PagedList<ViewItem>>()
.AfterMap((s, d) => Mapper.Map<List<DbItem>, List<ViewItem>>(s, d));

var dbList = new PagedList<DbItem>
{
new DbItem {Id = 1, Name = "a"},
new DbItem {Id = 2, Name = "b"}
};
dbList.TotalItems = 2;
dbList.CurrentPage = 1;
dbList.PageSize = 10;
var viewList = Mapper.Map<PagedList<DbItem>, PagedList<ViewItem>>(dbList);

Console.WriteLine(viewList.TotalItems);
Console.WriteLine(viewList.CurrentPage);
Console.WriteLine(viewList.PageSize);
Console.WriteLine(viewList[0].Id + " " + viewList[0].Name);
Console.WriteLine(viewList[1].Id + " " + viewList[1].Name);
Console.ReadLine();
}
}

关于Automapper map 自定义集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8228967/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com