将Model转换为ViewModel

时间:2014-01-09 16:48:40

标签: asp.net-mvc-4 entity-framework-4 viewmodel

我的桌子OWNER有一个模型

namespace MyApp.Models
{
    public partial class Owner
    {
        public int owner_id { get; set; }
        public string firstname { get; set; }
        public string lastname { get; set; }
        public string address { get; set; }
        public string city { get; set; }

        public virtual User User { get; set; }
    }
}

然后我有了我的ViewModel

public partial class OwnerData
{
    public string firstname { get; set; }
    public string lastname { get; set; }
    public string address { get; set; }
}

我的控制器

    public ActionResult Index()
    {
        //Create the object Owner based on the User Identity
        Owner owner = CustomDbFunctions.GetUserEntity(User, db).Owner;

//New instance of the ViewModel
        OwnerData ownerData = new OwnerData();

        ownerData.lastname = owner.lastname;
        ownerData.firstname = owner.firstname;
        ownerData.address = owner.address;

            return View(ownerData);

    }

有一种更简单的方法可以将我的owner转换为ownerData而无需重写我的对象的evry单一属性?

2 个答案:

答案 0 :(得分:2)

我认为我使用Automapper

解决了这个问题
public ActionResult Index()
{
    //Create the object Owner based on the User Identity
    Owner owner = CustomDbFunctions.GetUserEntity(User, db).Owner;

    Mapper.CreateMap<Owner, OwnerData>();
    OwnerData ownerData = Mapper.Map<Owner, OwnerData>(owner);

  return View(ownerData);
}

或者如果您更喜欢动态功能

    static TDestination GenerateMappingTable<TSource, TDestination>(TSource inputModel)
    {
        Mapper.CreateMap<TSource, TDestination>();
        return Mapper.Map<TSource, TDestination>(inputModel);
    }

要安装Automapper,只需执行

PM> Install-Package AutoMapper

从包管理器控制台。

答案 1 :(得分:1)

你可以使用object initizalizers。这会让它更简单,但我不确定这是你想要的

OwnerData ownerData = new OwnerData  { 
                          lastname = owner.lastname;
                          firstname = owner.firstname;
                          address = owner.address;
                          };