我想知道如何使用新值更新现有对象。我有一个简单的帐户对象,具有以下属性
public class Account
{
public int Id {get; set;}
public string Forename {get; set;}
public string Surname {get; set;}
public DateTime RegisterDate {get; set;}
public string Occupation {get; set;}
}
在我的项目中,我有一个简单的编辑方法,允许用户更新他们的Forename,Surname和Occupation。
public ActionResult Edit()
{
return View();
}
[HttpPost]
public ActionResult Edit(Account editFormDetails)
{
var accountDetails = GetAccountDetails(account.Id) //Gets a users existing details from db
return RedirectToAction("Index");
}
是否有一种使用editFromDetails对象中的新值更新现有对象(accountDetails)的好方法?我会做克隆,但是,我的编辑表单中的字段可以留空,所以我可能不需要更新。我在这个例子中简化了我的对象,使其不那么冗长。任何帮助都会很棒。
答案 0 :(得分:5)
使用NuGet安装名为AutoMapper
PM>安装包AutoMapper
安装完成后,您需要在要更新的每个类型之间创建地图,如果类型的属性匹配(如下面给出的示例中所示),则库将自动能够将这些属性相互映射......
void Main()
{
AutoMapper.Mapper.CreateMap<ChangeNameViewModel, User>()
.ForMember(member => member.FirstName, viewModel => viewModel.Condition(source => !string.IsNullOrWhiteSpace(source.FirstName)))
.ForMember(member => member.LastName, viewModel => viewModel.Condition(source => !string.IsNullOrWhiteSpace(source.LastName)));
User user = new User
{
FirstName = "Jane",
LastName = "Doe",
UserId = Guid.NewGuid().ToString()
};
ChangeNameViewModel model = new ChangeNameViewModel
{
FirstName = "John"
};
user = AutoMapper.Mapper.Map<ChangeNameViewModel, User>(model, user);
Console.WriteLine ("First name: {0}", user.FirstName);
Console.WriteLine ("Last name: {0}", user.LastName);
Console.WriteLine ("UserId: {0}", user.UserId);
// Output should be:
// ---------------------------
// First name: John
// Last name: Doe
// UserId: 9fd25bfd-c978-4287-8d3d-890d67834c23
// ---------------------------
}
public class User
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string UserId { get; set; }
}
public class ChangeNameViewModel
{
public string FirstName { get; set; }
public string LastName { get; set; }
}