2

Ok so I have this code to decide if an item exists in the db:

 foreach (var result in model.Results)
            {

                if (_ef.Results.Any(o=>o.Dog.DogId==result.Dog.DogId))
                {
                    result.Event = _ef.SingleEvent(result.Event.EventId);
                    result.Dog = _ef.SingleDog(result.Dog.DogId);
                    _ef.UpdateResult(result);
                }
                else
                {
                    result.Event = _ef.SingleEvent(result.Event.EventId);
                    result.Dog = _ef.SingleDog(result.Dog.DogId);
                    _ef.SaveResult(result);   

                }

            }

Now,if the item does not exist, I have this:

public void SaveResult(Result newResult)
        {
            _context.Results.Add(newResult);
            _context.SaveChanges();
        }

If it DOES exist, iwould like to update it:

 public void UpdateResult(Result result)
        {
           //Must be missing something here
          _context.SaveChanges();
        }

Am i missing something obvious here? Thanks

1
  • Had difficulties to post my answer... now it seems ok. Hope i will help you. Commented Nov 8, 2014 at 23:16

2 Answers 2

1

In my opinion the most reliable way to handle an update like this is to get the existing entity from the data store and then map the update data onto it. In other words, the result parameter object in the UpdateResult method will never actually make it into the database, just the data it carries. Something like this:

public void UpdateResult(Result result)
{
    var existing = _context.Results.FirstOrDefault(x => x.Dog.DogId.Equals(result.Dog.DogId));
    if (existing == null)
        throw new Exception("Result to update not found");

    existing.Name = result.Name;
    .... map other relevant properties here...

    _context.SaveChanges();
}

In some scenarios I would use some kind of automatic mapping, it depends on if there are business rules that need to be applied during the update. I prefer AutoMapper for automatic mapping.

Sign up to request clarification or add additional context in comments.

Comments

1

You need to change the object state before you call SaveChanges:

public void UpdateResult(Result result) {
    // The missing something:  
   _context.Entry(result).State = EntityState.Modified;
   _context.SaveChanges();
}

Another way would be to call:

_context.Attach(result);

Just before you start modifying your object. In this case you'd only need to call Save Changes afterwards and your're finished.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.