使用ViewModel值初始化模型

时间:2013-04-22 16:05:11

标签: asp.net-mvc asp.net-mvc-3

我想使用ViewModel中的Example模型中的值初始化一个新的Example模型。

var example = new Example { ExampleViewModel.Example};

以上返回错误:

  

无法使用集合初始值设定项初始化类型'ManagementOfChange.Models.ChangeRequest',因为它没有实现'System.Collections.IEnumerable'

这是否意味着我必须单独初始化每个值? e.g:

var example = new Example 
    { 
        value1 = ExampleViewModel.value1, 
        value2 = ExampleViewModel.value2 
    };

或者这只是我的语法问题?

2 个答案:

答案 0 :(得分:5)

我认为在你的情况下这样做是相同的:

var example = ExampleViewModel.Example;

答案 1 :(得分:1)

不需要创建对象来再次初始化属性。使用AutoMapper。实施例

创建地址类

    public class Address
    {
        public string Address1 { get; set; }

        public string Address2 { get; set; }

        public string City { get; set; }

        public string PostalCode { get; set; }

        public string Country { get; set; }
    }

创建客户类

    public class Customer
    {
        public string FirstName { get; set; }

        public string LastName { get; set; }

        public string Email { get; set; }

        public Address HomeAddress { get; set; }

        public string GetFullName()
        {
            return string.Format("{0} {1}", FirstName, LastName);
        }
    }

在Controller中,创建一个操作方法

方法 - 1(未创建映射时)

    public class AutoMapperController : Controller
    {
        public ActionResult Index()
        {
            List<Customer> customers = new List<Customer>();
            customers.Add(
                    new Customer 
                    { 
                        Email = "a@s.com", 
                        FirstName = "F1", 
                        LastName = "L1", 
                        HomeAddress = new Address 
                                            { 
                                                Address1 = "A1", 
                                                Address2 = "A2", 
                                                City = "C1", 
                                                Country = "Co1", 
                                                PostalCode = "P1" 
                                            } 
                    });

            AutoMapper.Mapper.CreateMap<Customer, CustomerListViewModel>();

            IList<CustomerListViewModel> viewModelList =
               AutoMapper.Mapper.Map<IList<Customer>, 
               IList<CustomerListViewModel>>(customers);
            return View(viewModelList);
        }
    }

现在,如果您看到下面的结果...我们在Customer类中有数据,并且在执行AutoMapping之后填充了CustomerListViewModel类..

enter image description here

方法 - 2创建映射时

创建一个名为MyMappings的类,并使用下面的代码定义映射。

public class MyMappings : Profile
{
    public const string NameOfProfile = "ContactDataProfile";

    public override string ProfileName
    {
        get
        {
            return NameOfProfile;
        }
    }

    protected override void Configure()
    {
        CreateMaps();
    }

    private static void CreateMaps()
    {
        Mapper.CreateMap<Customer, CustomerListViewModel>()
              .ForMember(dest => dest.Email, opt => opt.MapFrom(src => src.Email))
              .ForMember(dest => dest.FullName, opt => opt.MapFrom(src => src.FirstName + "." + src.LastName))
              .ForMember(dest => dest.HomeAddressCountry, opt => opt.MapFrom(src => src.HomeAddress))
              .IgnoreAllNonExisting();

        Mapper.AssertConfigurationIsValid();
    }
}

以下是您希望在某些类属性之间发送映射时所需的类

public static class AutoMapperExtensions
    {
        public static IMappingExpression<TSource, TDestination>
        IgnoreAllNonExisting<TSource, TDestination>(this IMappingExpression<TSource, TDestination> expression)
        {
            var sourceType = typeof(TSource);
            var destinationType = typeof(TDestination);
            var existingMaps = Mapper.GetAllTypeMaps().First(x => x.SourceType == sourceType && x.DestinationType == destinationType);
            foreach (var property in existingMaps.GetUnmappedPropertyNames())
            {
                expression.ForMember(property, opt => opt.Ignore());
            }
            return expression;
        }
    }

最后在Application Start Handler下的Global.asax类

AutoMapperConfigurator.Configure();

<强> Reference

您可以从软件包管理器控制台

下载它

enter image description here