0

I have 2 tables, Table_Books and Table_RentedBooks. When a user rents a book, I created a row in Table_Rented books with a IsDelete = 0 (it means it is still rented).

When user decides to deliver the book I want to change the column as IsDelete=1 but I get this error

Store update, insert, or delete statement affected an unexpected number of rows (0). Entities may have been modified or deleted since entities were loaded

I tried to do everything but still can't make it work. What should I change in my tables and codes?

Table_Books

BookID  int Unchecked,
CategoryID int  Unchecked,
BookName varchar(100)   Unchecked,
Writer varchar(50)  Unchecked,
Page int    Unchecked,
Recorddate date Unchecked,
UpdateDate date Checked,
Image varchar(300)  Unchecked,
Subject varchar(500)    Unchecked,
NumberofBooks int   Unchecked,
IsDeleted int   Checked
(BookID is the primary key)

Table_RentedBooks

RentID  int Unchecked,
BookID  int Unchecked,
UserID  int Unchecked,
Recorddate date Unchecked,
Deliverydate    Unchecked,
IsDeleted   int Unchecked,
(Recorddate is the primary key) 

RENT BOOK

[HttpPost]
public ActionResult RentBook(Table_Books book)
{
        User data = Session["useriz"] as User ;
    
        Book bookdata= Session["bookdata"] as Book;

        Table_RentedBooks z = new Table_RentedBooks ();
        var tbookid = book.BookID;
        var numberofbooks1=(int)bookdata.NumberofBooks -1;

        book.CategoryID = kitapdata.KategoriID;
        book.Image= kitapdata.KitapGorsel;
        book.NumberofBooks = numberofbooks1;

        bookrepo.Update(book);
            
        DateTime date = DateTime.Now;
        DateTime Recorddate = date;
        DateTime Deliverydate = date.AddDays(14);
        z.IsDeleted = 0;
        z.Deliverydate = Deliverydate   ;
        z.Recorddate = Recorddate ;
        z.UserID = data.UserID ;
        z.BookID = tbookid;

        Random rnd = new Random();
        int randomint = rnd.Next();
        z.RentID= randomint;

        rentedrepo.Add(z);
      
        return RedirectToAction("index", "Home");
    }
}

DELIVER BOOK (This method is the problem)

[HttpPost]
public ActionResult KitapTeslimEt(Table_Book book,Table_RentedBooks rentedbook)
{
        User data = Session["useriz"] as User ;
        
    
        Book bookdata= Session["bookdata"] as Book;

              Table_RentedBooks z = new Table_RentedBooks ();
             var tbookid = book.BookID;
            var numberofbooks1=(int)bookdata.NumberofBooks -1;
            book.CategoryID = kitapdata.KategoriID;
            book.Image= kitapdata.KitapGorsel;
            book.NumberofBooks = numberofbooks1;
            bookrepo.Update(book);
            
        DateTime date= DateTime.Now;
        DateTime Recorddate = date;
        DateTime Deliverydate   = date.AddDays(14);
            z.IsDeleted = 1;
            z.Deliverydate   = Deliverydate ;
            z.Recorddate = Recorddate ;
            z.UserID = data.UserID ;
            z.BookID= tbookid;
            Random rnd = new Random();
            int randomint = rnd.Next();
            z.RentID= randomint;
           rentedrepo.Update(z);
            
            return RedirectToAction("index", "Home");
        
    }

UPDATE METHOD

public void Update(T par) {

        try
        {
            db.SaveChanges();
        }
        catch (System.Data.Entity.Validation.DbEntityValidationException dbEx)
        {
            Exception raise = dbEx;
            foreach (var validationErrors in dbEx.EntityValidationErrors)
            {
                foreach (var validationError in validationErrors.ValidationErrors)
                {
                    string message = string.Format("{0}:{1}",
                        validationErrors.Entry.Entity.ToString(),
                        validationError.ErrorMessage);
                    // raise a new exception nesting
                    // the current instance as InnerException
                    raise = new InvalidOperationException(message, raise);
                }
            }
            throw raise;
        }
    }
    


marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
  • db.SaveChanges(); has a link between the c# classes and database. Error "Entities may have been modified" indicates the link was broken. Probably some place in code the new instance of the dbEntity was created or the connection was broken between the c# and the database. – jdweng Sep 08 '22 at 11:35
  • @jdweng I don't get an error when I create a new record instead updating it. I don't know what do to. Only thing I want to change in my code is IsDelete column. –  Sep 08 '22 at 11:38
  • I only see the code posted. I can't tell anything else. I would check the database log files to see if there is more info. There are four sql command types 1) Select 2) Insert 3) Update 4) Delete. If you are using a command in Net to update database than the Update Command need to be added. Net has a CommandBuilder which takes the Select command and automatically creates the other 3 commands. I do not know if you are using a sql command or a different method to query the database. I just telling you what I know. – jdweng Sep 08 '22 at 12:01
  • Check whether have passed the primary key of the table. It means either u have not passed the key to the record or the record that with the key u passed has been removed. – Yat Fei Leong Sep 08 '22 at 12:36
  • Does this answer your question? [Entity Framework: "Store update, insert, or delete statement affected an unexpected number of rows (0)."](https://stackoverflow.com/questions/1836173/entity-framework-store-update-insert-or-delete-statement-affected-an-unexpec) – Kiran Joshi Sep 08 '22 at 12:41

1 Answers1

0

You try to update z as RentedBook but you have not define it to update

 [HttpPost]
    public ActionResult KitapTeslimEt(Table_Book book,Table_RentedBooks rentedbook)
    {
            User data = Session["useriz"] as User ;
            
    
        Book bookdata= Session["bookdata"] as Book;

              Table_RentedBooks z = new Table_RentedBooks ();

            // you define z is new RentedBook here. I think u forget to call the book here and therefore there is no entity to update
            //try add this
            z = db.Table_RentedBooks.Find(rentedbook.Recorddate);
             var tbookid = book.BookID;
            var numberofbooks1=(int)bookdata.NumberofBooks -1;
            book.CategoryID = kitapdata.KategoriID;
            book.Image= kitapdata.KitapGorsel;
            book.NumberofBooks = numberofbooks1;
            bookrepo.Update(book);
            
        DateTime date= DateTime.Now;
        DateTime Recorddate = date;
        DateTime Deliverydate   = date.AddDays(14);
            z.IsDeleted = 1;
            z.Deliverydate   = Deliverydate ;
            z.Recorddate = Recorddate ;
            z.UserID = data.UserID ;
            z.BookID= tbookid;
            Random rnd = new Random();
            int randomint = rnd.Next();
            z.RentID= randomint;
           rentedrepo.Update(z);
            
            return RedirectToAction("index", "Home");
        
    }
Yat Fei Leong
  • 751
  • 1
  • 6
  • 10