使用新值更新现有对象
本文关键字:对象 更新 新值 | 更新日期: 2023-09-27 18:24:08
我想知道如何用新值更新现有对象。我有一个简单的帐户对象,具有以下属性
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;}
}
在我的项目中,我有一个简单的编辑方法,允许用户更新他们的名字,姓氏和职业。
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)的好方法?我会克隆,但是,编辑表单中的字段可以留空,所以我可能不需要更新。在这个例子中,我简化了我的对象,使它不那么冗长。任何帮助都会很棒。
使用NuGet安装一个名为AutoMapper
的库
PM>安装包自动映射
安装后,您需要在要更新的每个类型之间创建映射,如果类型的属性匹配(如我下面给出的示例),则库将能够自动将这些属性映射到彼此。。。
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; }
}