0

I have this code. The code will find the correct log but won't save any changes back to the database. How would I get it to save?

var query = from log in db.Logs
            where log.LogID == id
            select log;

foreach (Log log in query)
{
    log.DateTimeResolved = System.DateTime.Now;
    db.Entry(query).State = EntityState.Modified;
}

try
{
    db.SaveChanges();
}
catch (Exception e)
{ }

return RedirectToAction("Index");   
9
  • 6
    Don't use an empty catch block - any error you get is being ignored. Commented Mar 3, 2014 at 16:33
  • 3
    db.Entry(log) but Still, you should not need that. Commented Mar 3, 2014 at 16:33
  • The assumption is that you are throwing an error, catching it, and discarding it. What, if anything, is the value of e when you debug this? Commented Mar 3, 2014 at 16:35
  • Does this go in the foreach loop? Commented Mar 3, 2014 at 16:35
  • 1
    You shouldn't have to set the state to modified. The state tracking should do that automatically. Commented Mar 3, 2014 at 16:36

2 Answers 2

1

Well it's hard to say since you're ignoring any exception that is thrown, but this looks suspect:

foreach (Log log in query)
{
    log.DateTimeResolved = System.DateTime.Now;
    db.Entry(query).State = EntityState.Modified;
}            ^---  should be "log" instead of "query"?

My guess is that since Entry() takes an object it compiles but at runtime you're getting an error and ignoring it. As stated in the comments, you should not need to explicitly set the state to Modified since you're modifying the entity directly. I think you just need:

foreach (Log log in query)
{
    log.DateTimeResolved = System.DateTime.Now;
} 
Sign up to request clarification or add additional context in comments.

1 Comment

db.SaveChanges() throws Validation failed for one or more entities. See 'EntityValidationErrors' property for more details.
0

There was a Required field in my Log entity class causing the problem. Though why would it need to set this again if i'm just updating and not adding?

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.