AutoMapper Profile用法


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using AutoMapper;

namespace MvcAutoMapper.AutoMapper
{
    public class Configuration
    {
        public static void Configure()
        {
            Mapper.Initialize(cfg =>
            {
                cfg.AddProfile<UserProfile>();
            });
        }
    }
}

  

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using AutoMapper;

namespace MvcAutoMapper.AutoMapper.Profiles
{
    public class UserProfile:Profile
    {

        protected override void Configure()
        {
            CreateMap<Models.User, Models.UserDto>();

        }
    }
}

  

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using AutoMapper;

namespace MyMvc.AutoMapper
{
    public static class AutoMapperForMvc
    {
        public static void Register()
        {
            Mapper.Initialize(x =>
            {
                x.AddProfile<UserProfile>();
            });

            //在程序啟動時對所有的配置進行嚴格驗證
            Mapper.AssertConfigurationIsValid();
        }
    }
}

  

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using AutoMapper;

namespace MyMvc.AutoMapper
{
    public class UserProfile:Profile
    {
        public UserProfile()
        {
            base.CreateMap<Models.User, Models.UserView>()
                //映射前
                .BeforeMap((s, t) =>
                {
                    s.Age += 10;
                })
                //映射后
                .AfterMap((s, t) =>
                {
                    t.Age += 10;
                })
                //條件判斷 
                //年齡不大於10 不映射年齡這個屬性的值,那值就是默認的0,但是映射后+10,所以就是10
                .ForMember(t=>t.Age,o=>o.Condition(s=>s.Age>30))
                //空值
                .ForMember(t=>t.Name, o=>o.NullSubstitute("無名氏")) 
                .ForMember(x=>x.time,x=>x.MapFrom(s=>s.add_time))
                //反向映射
                .ReverseMap(); 
        }
    }
}

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM