ASPCoder1450
ASPCoder1450

Reputation: 1651

Saving Changes to Database Using LINQ and ASP.NET

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");   

Upvotes: 0

Views: 676

Answers (2)

ASPCoder1450
ASPCoder1450

Reputation: 1651

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?

Upvotes: 0

D Stanley
D Stanley

Reputation: 152556

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

Upvotes: 1

Related Questions