Home > Back-end >  how to decrease value in database in mvc?
how to decrease value in database in mvc?

Time:09-06

I have a table called Table_Books and I keep the number of books for each book as int. When user rents a book, I want to decrease the quantity of books in database. When it's 0 , a warning should appear like 'You can't rent this book'. How can I do this?

My "Rent a Book" method (even though it decreases, nothing changes in database):

[HttpPost]
public ActionResult RentBook(Table_Books book)
{
        User data = TempData["userdata"] as User ;

        if (data == null)
        {
            ViewBag.ErrorMessage = "error!";
            return RedirectToAction("index", "login");
        }
        else
        {
            Table_RentedBooks = new Table_RentedBooks ();
           
            var tbookid = book.BookID;
            var numberofbooks1=book.NumberofBooks-1;
            book.NumberofBooks= numberofbooks1;
            bookrepo.Update(book);
            db.SaveChanges();
          
            DateTime d1= DateTime.Now;
            DateTime recorddate= d1;
            DateTime deliverydate= d1.AddDays(14);

            z.DeliveryDate = deliverydate;
            z.RecordDate = recorddate;
            z.UserID = data.UserID;
            z.BookID = tbookid;
            
            rentedrepo.Add(z);
        
            return RedirectToAction("index", "Home");
        }
}

My repository methods

public class GenericRepository<T> where T:class,new()
{
    LibraryEntities db = new LibraryEntities();

    public List<T> List()
    {
        return db.Set<T>().ToList();
    }

    public void Add(T par)
    {
        db.Set<T>().Add(par);
        db.SaveChanges();
    }

    public void Update(T par)
    {
        db.SaveChanges();
    }

    public T TGet(int id)
    {
        return db.Set<T>().Find(id);
    }

    public T Find(Expression<Func<T,bool>> where)
    {
        return db.Set<T>().FirstOrDefault(where);
    }

    public void Delete(T par)
    {
        db.Set<T>().Remove(par);
        db.SaveChanges();
    }
}
<connectionStrings>
    <add name="LibraryEntities" connectionString="metadata=res://*/Models.Model1.csdl|res://*/Models.Model1.ssdl|res://*/Models.Model1.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=(localdb)\Local;initial catalog=Library;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework&quot;" providerName="System.Data.EntityClient" />
  </connectionStrings>

CodePudding user response:

The reason your data is not changing is that you are modifing the book that you got from your post request and your DbContext has no track of it. there are 2 solutions:

1.You can retrive the book from dbContext first and then modify it and call saveChange()

2.You should change the state of the entity to modified before you saveChanges. Somthing like this:

public void Update(T par)
{
    db.Entry(book).State = 
    Microsoft.EntityFrameworkCore.EntityState.Modified;
    db.SaveChanges();
}

CodePudding user response:

Despite what you say about the AppData folder being empty, given your connectionString I am pretty sure that your data is being regenerated. Take a look at this link. of particular relevance is:

The LocalDB setup program uses the SqlLocalDB.msi program to install the necessary files on the computer. Once installed, LocalDB is an instance of SQL Server Express that can create and open SQL Server databases. The system database files for the database are stored in the local AppData path, which is normally hidden. For example, C:\Users<user>\AppData\Local\Microsoft\Microsoft SQL Server Local DB\Instances\LocalDBApp1. User database files are stored where the user designates, typically somewhere in the C:\Users<user>\Documents
folder.

  • Related