asp.net AutoMapper:如果源中不存在属性,则保留目标值

m0rkklqb  于 2023-10-21  发布在  .NET
关注(0)|答案(2)|浏览(138)

我试着搜索了很多,并尝试不同的选择,但似乎没有工作。
我使用的是ASP.net Identity 2.0,我有UpdateProfileViewModel。当更新用户信息时,我想将UpdateProfileViewModelMap到ApplicationUser(即身份模型);但是我想保留这些值,我从用户的数据库中得到的。例如,电子邮件地址和电子邮件地址,不需要更改。
我试着做:

Mapper.CreateMap<UpdateProfileViewModel, ApplicationUser>()
.ForMember(dest => dest.Email, opt => opt.Ignore());

但我仍然得到的电子邮件为空Map后:

var user = await UserManager.FindByIdAsync(User.Identity.GetUserId());
user = Mapper.Map<UpdateProfileViewModel, ApplicationUser>(model);

我也试过,但不起作用:

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.Equals(sourceType) && x.DestinationType.Equals(destinationType));
        foreach (var property in existingMaps.GetUnmappedPropertyNames())
        {
            expression.ForMember(property, opt => opt.Ignore());
        }
        return expression;
    }

然后:

Mapper.CreateMap<UpdateProfileViewModel, ApplicationUser>()
.IgnoreAllNonExisting();
8e2ybdfx

8e2ybdfx1#

你所需要做的就是在你的源和目标类型之间创建一个Map:

Mapper.CreateMap<UpdateProfileViewModel, ApplicationUser>();

然后执行Map:

UpdateProfileViewModel viewModel = ... this comes from your view, probably bound
ApplicationUser user = await UserManager.FindByIdAsync(User.Identity.GetUserId());
Mapper.Map(viewModel, user);

// at this stage the user domain model will only have the properties present
// in the view model updated. All the other properties will remain unchanged
// You could now go ahead and persist the updated 'user' domain model in your
// datastore
hc2pp10m

hc2pp10m2#

Map器将返回一个新的对象时,分配给目标对象,而不是你必须使用Map传递源和目标作为参数。

public class SourceObjectModel 
{
    public string Name { get; set; }
}

public class DestinationObjectModel
{
    public int Id { get; set; }
    public string Name { get; set; }
}

SourceObjectModel sourceObj = new SourceObjectModel() {Name = "foo"};
DestinationObjectModel destinObj = new DestinationObjectModel(){Id = 1};

/*update only "name" in destinObj*/
_mapper.Map<SourceObjectModel, DestinationObjectModel>(sourceObj, destinObj);

相关问题