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

标签 c# asp.net .net automapper

脱离我之前的问题 -> 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/

相关文章:

c# - 强制将 excel 窗口带到前面?

asp.net - 代码可重用性 - App_Code 或 BIN 或 UserControls?

c# - 我可以使用C#锁来防止Web应用程序中的SQL Server死锁吗?

.net - 是否有可用的开源 .Net SQL 编辑器组件?

c# - CS0144 - C# - 无法创建抽象类或接口(interface)的实例

c# - 如何返回包含在 1 个函数中找到的总行数的记录

c# - 解决方案中 Autofac 模块类的放置

asp.net - 如何从 JavaScript 访问 ASPxTextBox 的值

c# - 通过 PrintToPrinter 打印我的 Crystal 报表后数据丢失

c# - 保存 .NET 用户设置需要很长时间