私はさまざまな同様の投稿を調べましたが、これで私のやり方の誤りを見つけることができません。基本的に、「設定」オブジェクトのさまざまな部分を更新する2つのビューがあります。ビューモデルには2つのプロパティのいずれかが含まれており、どちらが設定されているかに応じて、もう一方を無視する必要があります。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」に置き換えられます。
誰かが私のやり方の誤りを見つけることができますか?