gpt4 book ai didi

c# - Automapper 不忽略嵌套属性

转载 作者:行者123 更新时间:2023-11-30 17:09:55 26 4
gpt4 key购买 nike

我已经浏览过各种类似的帖子,但无法发现我的方法有这个错误。基本上我有两个 View 更新“设置”对象的不同部分。 View 模型包含两个属性之一,根据设置的属性,应该忽略另一个。当它是 ViewModel ==> Entity direct 时,它工作正常,但是当 Automapper 尝试更新嵌套对象时,它会失败。

我有以下对象结构:

public class Account
{
public int AccountId { get; set; }
public DateTime DateToBeIgnored { get; set; }
public AccountSetting Settings { get; set; }
}

public class AccountSetting
{
public string PropertyOne { get; set; }
public string PropertyTwo { get; set; }
}

public class AccountViewModel
{
public int AccountId { get; set; }
public DateTime DateToBeIgnored { get; set; }
public AccountSettingViewModel Settings { get; set; }
}

public class AccountSettingViewModel
{
public string PropertyTwo { get; set; }
}

public class OtherAccountSettingViewModel
{
public string PropertyOne { get; set; }
}

通过映射:

void WireUpMappings()
{
// From the entities to the view models
Mapper.CreateMap<Account, AccountViewModel>();
Mapper.CreateMap<AccountSetting, AccountSettingViewModel>();
Mapper.CreateMap<AccountSetting, OtherAccountSettingViewModel>();

// From the view models to the entities
Mapper.CreateMap<AccountViewModel, Account>()
.ForMember(dest => dest.DateToBeIgnored, opt => opt.Ignore());

Mapper.CreateMap<AccountSettingViewModel, AccountSetting>()
.ForMember(dest => dest.PropertyTwo, opt => opt.Ignore());

Mapper.CreateMap<OtherAccountSettingViewModel, AccountSetting>()
.ForMember(dest => dest.PropertyOne, opt => opt.Ignore());

Mapper.AssertConfigurationIsValid();
}

映射 [OtherAccountSettingViewModel --> AccountSetting] 时,仅分配了属性“PropertyTwo”(并且“PropertyOne”的原始值保持不变)-这是我所期望的。

但是,当映射 [AccountViewModel --> Account] 时,“DateToBeIgnored”将按预期被忽略,而 Account.AccountSetting.PropertyTwo 的先前值将替换为“null”。

谁能发现我方法的错误?

最佳答案

解决方法如下:

[TestMethod]
public void TestMethod1()
{
Mapper.CreateMap<AccountViewModel, Account>()
.ForMember(dest => dest.DateToBeIgnored, opt => opt.Ignore())
.ForMember(dest=>dest.Settings, opt=>opt.UseDestinationValue());

Mapper.CreateMap<AccountSettingViewModel, AccountSetting>()
.ForMember(dest=>dest.PropertyOne, opt=>opt.Ignore())
.ForMember(dest => dest.PropertyTwo, opt => opt.MapFrom(a => a.PropertyTwo));

Mapper.AssertConfigurationIsValid();

AccountViewModel viewmodel = new AccountViewModel()
{
AccountId = 3,
DateToBeIgnored = DateTime.Now,
Settings = new AccountSettingViewModel() { PropertyTwo = "AccountSettingViewModelPropTwo" }
};

Account account = new Account()
{
AccountId = 10,
DateToBeIgnored = DateTime.Now,
Settings = new AccountSetting() { PropertyOne = "AccountPropOne", PropertyTwo = "AccountPropTwo" }
};

account = Mapper.Map<AccountViewModel, Account>(viewmodel, account);

Assert.IsNotNull(account);

}

result

关于c# - Automapper 不忽略嵌套属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12439132/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com