user3529453
user3529453

Reputation: 71

Update existing object with new values

I was wondering how you could update an existing object with new values. I have a simple account object with the following properties

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;}
}

In my project I have a simple edit method which allows a user to update their Forename, Surname and 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");
}

Is there a nice way of updating the existing object(accountDetails) with the new values from the editFromDetails object? I would do clone, however, the fields in my edit form can be left empty, so I may not need to update. I've simplified my object in this example to make it less verbose. Any help would be great.

Upvotes: 1

Views: 2319

Answers (1)

Aydin
Aydin

Reputation: 15294

Use NuGet to install a library called AutoMapper

PM> Install-Package AutoMapper

Once installed, you will need to create maps between each Type that you wish to update, if the properties of the types match (like in the example I've given below), then the library will automatically be able to map those properties to each other...

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; }
}

Upvotes: 5

Related Questions