Entity Framework Linq update data not working

I want to update the entity object record but it do not show exception but it do not update the record.

in issue_detail objetct previously it contains a null value, after user update data it calls the below method

public Boolean bookReturnedUpdate(Issue_Detail issue)
    {

        BookController bookController = new BookController();
        int bookID = (int) issue.book_id;
        Book_Detail book = bookController.findByBookID(bookID);
        int noOfCopies = (int) book.no_of_copies;

        book.no_of_copies = ++noOfCopies;
        Console.Write("just before the update");
        bookController.updateBook(book);

        Console.WriteLine("Issue ID" +issue.issue_id);
        Boolean status = false;
        try
        {
            using (var db = new ModelDB())
            {



                DateTime issueD = (DateTime) issue.return_date;
                Console.WriteLine("Details " + issueD); // here I can see the date is update and it contains the new date I have inserted

                db.Entry(issue).State = EntityState.Modified;

                db.Issue_Detail.Attach(issue);

                db.SaveChanges(); // this returns 0 when I have checked wit h Console.WriteLine

                status = true;

            }
        }
        catch (Exception ex)
        {
            Console.WriteLine("Book return update error " + ex.InnerException);
        }
        return status;
    }

But after the update is done it still remain the old null record as it is. 在这里输入图像描述

Thank you.

I have tried just db.SaveChanges() it also did not work

If anyone need the full repository please check the following Github link https://github.com/ccmcwolf/LibraryManagementSystem


你可以这样做:

 dbContext.Issue_Detail.Attach(issue);
 var entry = dbContext.Entry(issue);
 entry.State = EntityState.Modified;
 db.SaveChanges();

I think the problem is your db.Issue_Detail.Attach(issue); call right before saving...

DbSet.Attach

Note that entities that are already in the context in some other state will have their state set to Unchanged

This means you lose your State = Modified right after setting it.


If you are updating an existing record, the easiest way is to first retrieve the item from the database, and then update the values.

from the relevant part in your code (untested code below):

using (var db = new ModelDB())
{

    var entity = db.Issue_Detail.FirstOrDefault(i => i.issue_id == (int)issue.issue_id);
    if (entity == null)
    {
        //handle error:
        throw new Exception("Issue not found");
    }
    //here we update the properties:
    db.Entry(entity).CurrentValues.SetValues(issue);
    db.SaveChanges();

    status = true;
}
链接地址: http://www.djcxy.com/p/33588.html

上一篇: 我如何获得实体的旧价值?

下一篇: 实体框架Linq更新数据不起作用