Initializing model with ViewModel values

2019-07-18 19:40发布

问题:

I want to initialize a new Example model with values from an Example model within the ViewModel.

var example = new Example { ExampleViewModel.Example};

The above returns the error:

Cannot initialize type 'ManagementOfChange.Models.ChangeRequest' with a collection initializer because it does not implement 'System.Collections.IEnumerable'

Does this mean I have to initialize every value individually? e.g:

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

Or is this just a problem with my syntax?

回答1:

I think in your case it is the same to do this:

var example = ExampleViewModel.Example;


回答2:

It is not required to create the object to initialize the properties again. Use AutoMapper. Example

Create an Address Class

    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; }
    }

Create Customer Class

    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);
        }
    }

In Controller, Create a Action Method

Approach - 1 (When the Mappings are not created)

    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);
        }
    }

Now, if you see the results below... We have data in Customer class and after doing the AutoMapping CustomerListViewModel class is populated..

Approach - 2 When mappings are created

Create a class called MyMappings and define the mappings using below code.

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();
    }
}

Following is the class needed when you want to ship mapping between some class properties

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;
        }
    }

Finally in Global.asax class under Application Start Handler

AutoMapperConfigurator.Configure();

Reference

You can download it from package Manager Console