怪奇物语

怪奇物语

首页 新随笔 联系 管理

AutoMapper的默认映射规则 convertions map complex object to flat/simple ones

Default conventions

AutoMapper uses the following conventions:

  • It will automatically map properties with the same names.

  • If the source object has some association with other objects,
    then it will try to map with properties on the destination object
    whose name is a combination of the source class name and property name in the Pascal case.

如下所示:

UserViewModel userViewModel = _mapper.Map<UserViewModel>(user);
public class User
{
    public Address Address { get; set; }
}
public class Address
{
    public string Country { get; set; }
}
public class UserViewModel
{
    [Display(Name = "Country")]
    public string AddressCountry { get; set; }
}
  • It will try to map methods on the source object
    which has a Get prefix with a property
    on the destination object
    with the name excluding the Get prefix.

如下所示:

UserViewModel userViewModel = _mapper.Map<UserViewModel>(user);
public class User
{
    public string GetFullName()
    {
        return $"{this.LastName}, {this.FirstName}";
    }
}
public class UserViewModel
{
    [Display(Name = "Full Name")]
    public string FullName { get; set; }
}

If we follow these conventions, AutoMapper will automatically map our objects. Otherwise, we’ll need to configure AutoMapper using Fluent API.

例子

Let’s modify our User object by adding a child object Address:

public class User
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Email { get; set; }
    public Address Address { get; set; }

    public string GetFullName()
    {
        return $"{this.LastName}, {this.FirstName}";
    }
}

And here’s how the Address class looks like:

public class Address
{
    public int Id { get; set; }
    public string Door { get; set; }
    public string Street1 { get; set; }
    public string Street2 { get; set; }
    public string City { get; set; }
    public string State { get; set; }
    public string Country { get; set; }
    public string ZipCode { get; set; }
}

Also, note that we have added a method GetFullName() to get the user’s full name.

Let’s modify the UserViewModel class:

public class UserViewModel
{
    [Display(Name = "Full Name")]
    public string FullName { get; set; }

    [Display(Name = "Country")]
    public string AddressCountry { get; set; }

    public string Email { get; set; }
}

Now, Let’s modify the profile class to use the default conventions:

public UserProfile()
{
    CreateMap<User, UserViewModel>();
}
posted on 2024-12-26 08:00  超级无敌美少男战士  阅读(36)  评论(0)    收藏  举报