使用ValueInjecter具有不同属性名称的对象之间进行映射 [英] Using ValueInjecter to map between objects with different property names

查看:144
本文介绍了使用ValueInjecter具有不同属性名称的对象之间进行映射的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何使用不同的属性名称从对象的属性映射到另一个对象?

How do I map a property from an object to another object with a different property name?

我有一个产品类,看起来像这样:

I have a Product class that looks like this:

public class Product : IEntity
{
     public int Id { get; set; }
     public string Name { get; set; }
}

和视图模型如下:

public class ProductSpecificationAddViewModel
{
     public int ProductId { get; set; }
     public string ProductName { get; set; }
}

我需要做以下映射:

I need to do the following mapping:

Product.Id => ProductSpecificationAddViewModel.ProductId
Product.Name =>ProductSpecificationAddViewModel.ProductName

下面是我的操作方法:

public ActionResult Add(int id)
{
     Product product = productService.GetById(id);

     // Mapping
     //ProductSpecificationAddViewModel viewModel = new ProductSpecificationAddViewModel();
     //viewModel.InjectFrom(product);

     return View(viewModel);
}

我将如何做到这一点?

How would I do this?

推荐答案

如果您使用的是ValueInjecter那么你就写一个ConventionInjection。看到第二个样品<一个href=\"http://valueinjecter.$c$cplex.com/wikipage?title=step%20by%20step%20explanation&referringTitle=Home\">here

If you are using ValueInjecter then you would write a ConventionInjection. See the second sample here

    public class PropToTypeProp : ConventionInjection
    {
        protected override bool Match(ConventionInfo c)
        {
            return c.TargetProp.Name == c.Source.Type.Name + c.TargetProp.Name;
        }
    }

此注入将执行从TSource的所有属性*为TTarget.TSource + *,所以你做的:

this injection will do from all properties of TSource.* to TTarget.TSource+*, so you do:

vm.InjectFrom<PropToTypeProp>(product);

这篇关于使用ValueInjecter具有不同属性名称的对象之间进行映射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆