gpt4 book ai didi

c# - 如何使用 Automapper 函数调用递归地将实体映射到 View 模型?

转载 作者:太空宇宙 更新时间:2023-11-03 19:11:05 25 4
gpt4 key购买 nike

脱离我之前的问题 -> How to map .NET function call to property automatically?

我有一些相关的实体对象,我想映射到 View 模型,每个映射到 View 模型都需要调用一个映射函数。

棘手的部分是实体函数返回另一个需要映射到它的 View 模型的实体。流程有点像这样。

CartEntity > CartViewModel > CartEntity.GetCartItems() > CartViewModel.CartItems > CartEntity.GetCartItems().GetItem() > CartViewModel.CartItems.Item > CartEntity.GetCartItems().GetItem().GetProduct() > CartViewModel.CartItems.Item.Product

这里是类,我在其中尝试递归构建嵌套集,其中填充了每个对象。

实体:

public class CartEntity {
public long Id {get; set;}
public List<CartItem> GetCartItems() {
return Repository.GetAll<CartItem>();
}
}

public class CartItem {
public long Id {get; set;}
public long ItemId {get ; set;}
public Item GetItem() {
return Repository.Get<Item>(ItemId);
}
}

public class Item {
public long Id {get; set;}
public long ProductId {get; set;}
public Item GetProduct() {
return Repository.Get<Product>(ProductId);
}
}
public class Product {
public long Id {get; set;}
}

查看模型:

public class CartViewModel {
public long Id {get; set;}
public List<CartItemViewModel> {get; set; }
}

public class CartItemViewModel {
public long Id {get; set;}
public ItemViewModel Item {get; set; }
}

public class ItemViewModel {
public long Id {get; set;}
public ProductViewModel Product {get; set; }
}

public class ProductViewModel {
public long Id {get; set;}
}

最佳答案

你不需要做任何复杂的事情,AutoMapper 支持这个:

// one time config
Mapper.CreateMap<CartEntity, CartViewModel>();
Mapper.CreateMap<CartItem, CartItemViewModel>();
Mapper.CreateMap<Item, ItemViewModel>();
Mapper.CreateMap<Product, ProductViewModel>();
Mapper.AssertConfigurationIsValid();

// whenever you map
CartEntity cart = // whatever
CartViewModel vm = Mapper.Map<CartViewModel>(cart);

关于c# - 如何使用 Automapper 函数调用递归地将实体映射到 View 模型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20573600/

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