使用automapper进行映射

时间:2012-06-28 15:27:01

标签: asp.net-mvc automapper

我有一个名为word的模型。

这是我的单词模型

public class Word : BaseFieldsTables
{
    int ID { get; set; }
    string Name { get; set; }
    Guid UniqID { get; set; }
    DateTime CreatedDate { get; set; }
    byte[] RowVersion { set; get; }
    public string Text { get; set; }
    public virtual Category Category { get; set; }
    public int CategoryID { get; set; }
    public virtual Language Language { get; set; }
    public int LanguageID { get; set; }

    public virtual ICollection<Picture> Pictures { get; set; }

    [InverseProperty("MainWord")]
    public virtual ICollection<RelationshipBetweenWords> MainWords { get; set; }

    [InverseProperty("RelatedWord")]
    public virtual ICollection<RelationshipBetweenWords> RelatedWords { get; set; }
}

单词有一个类别和语言......

例如这是我的语言模型

    public class Language : BaseFieldsTables
    {
       int ID { get; set; }
        string Name { get; set; }
        Guid UniqID { get; set; }
        DateTime CreatedDate { get; set; }
        byte[] RowVersion { set; get; }
        public virtual ICollection<Word> Words { get; set; }
    }

我有像这样的单词viewmodel

public class WordViewModel

    public string Name { get; set; }


    public IList<SelectListItem> Categories { set; get; }


    [HiddenInput(DisplayValue = false)]
    public int SelectedCategoryID { set; get; }


    public IList<SelectListItem> Languages { set; get; }



    [HiddenInput(DisplayValue = false)]
    public int SelectedLanguageID { set; get; }
}

这是我的控制器

public ActionResult Index(
    {
        IList<Word> list = _wordService.GetAll();

    }

我想用语言名和类别名称获取所有单词和地图(auotomapper)到我的WordViewModel并在我的视图中返回请帮助我,如果我必须更改我的wordviewmodel或...以及如何map.tnx

1 个答案:

答案 0 :(得分:0)

哦,我找到了它

public ActionResult Index()
        {
            var orders = _respository.GetAll();

            AutoMapper.Mapper.CreateMap<Order, OrderDto>()
                .ForMember(dest => dest.OrderNumber, opt => opt.MapFrom(src => src.OrderNo))
                .ForMember(dest => dest.OrderItemsDto, opt => opt.Ignore());

            var model = AutoMapper.Mapper.Map<IEnumerable<Order>, IEnumerable<OrderDto>>(orders);

            return View(model);
        }
//Razor View Code
<h2>Orders</h2>
<table>
    <tr>
        <th>Order Number</th>
        <th>Name</th>
        <th>Total</th>
    </tr>
@foreach (var item in Model)
{
    <tr>
        <td>@item.OrderNumber</td>
        <td>@item.CustomerName</td>
        <td>$@item.Total</td>
    </tr>
}
</table>