[英]How to modify value of object inside deleting object? [MVC, JSON, JavaScript]
我有一個很大的MVC項目,這是我的API控制器:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using AutoMapper;
using Library.Dtos;
using Library.Models;
using System.Data.Entity;
namespace Library.Controllers.Api
{
public class RentalsController : ApiController
{
private ApplicationDbContext _context;
public RentalsController()
{
_context = new ApplicationDbContext();
}
// GET /api/rentals
public IHttpActionResult GetRentals(string query = null)
{
var rentalsQuery = _context.Rentals
.Include(r => r.Customer)
.Include(r => r.Book);
var rentalDtos = rentalsQuery
.ToList()
.Select(Mapper.Map<Rental, RentalDto>);
return Ok(rentalDtos);
}
// GET /api/rentals/1
public IHttpActionResult GetRental(int id)
{
var rental = _context.Rentals.SingleOrDefault(r => r.Id == id);
if (rental == null)
return NotFound();
return Ok(Mapper.Map<Rental, RentalDto>(rental));
}
[HttpDelete]
public IHttpActionResult DeleteRental(int id)
{
var rentalInDb = _context.Rentals.SingleOrDefault(c => c.Id == id);
if (rentalInDb == null)
return NotFound();
var book = _context.Books.Single(c => c.Id == id);
book.NumberAvailable++;
_context.Rentals.Remove(rentalInDb);
_context.SaveChanges();
return Ok();
}
}
}
這是我的控制器:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Runtime.InteropServices;
using System.Web.Http;
using AutoMapper;
using Library.Dtos;
using Library.Models;
namespace Library.Controllers.Api
{
public class NewRentalsController : ApiController
{
private ApplicationDbContext _context;
public NewRentalsController()
{
_context = new ApplicationDbContext();
}
[HttpPost]
public IHttpActionResult CreateNewRentals(NewRentalDto newRental)
{
var customer = _context.Customers.Single(c => c.Id == newRental.CustomerId);
var books = _context.Books.Where(m => newRental.BookIds.Contains(m.Id)).ToList(); //SELECT * FROM Books WHERE Id IN (1,2,3 etc)
foreach (var book in books)
{
if (book.NumberAvailable == 0)
return BadRequest("Ksiazka jest niedostepna.");
book.NumberAvailable--;
var rental = new Rental
{
Customer = customer,
Book = book,
DateRented = DateTime.Now
};
_context.Rentals.Add(rental);
}
_context.SaveChanges();
return Ok();
}
}
}
這是我執行刪除操作的索引視圖:
@model IEnumerable<Library.Models.Rental>
@{
ViewBag.Title = "Wypozyczenia";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Rentals</h2>
<table id="rentals" class="table table-bordered table-hover">
<thead>
<tr>
<th>Klient</th>
<th>Tytul</th>
<th>Data wypozyczenia</th>
<th>Akcje</th>
</tr>
</thead>
<tbody></tbody>
</table>
@section scripts
{
<script>
$(document).ready(function () {
var table = $("#rentals").DataTable({
ajax: {
url: "/api/rentals",
dataSrc: ""
},
columns: [
{
data: "Customer.Name"
},
{
data: "Book.Name"
},
{
data: "DateRented"
},
{
data: "Id",
render: function (data) {
return "<button class='btn-link js-delete' data-rentals-id=" + data + ">Zwrot zamowienia.</button>";
}
}
]
});
$("#rentals").on("click", ".js-delete",
function () {
var button = $(this);
if (confirm("Na pewno?")) {
$.ajax({
url: "/api/rentals/" + button.attr("data-rentals-id"),
method: "DELETE",
success: function () {
//datatable methods - row, remove and draw
table.row(button.parents("tr")).remove().draw();
}
});
}
});
});
</script>
}
最后,這是我的租賃課程(模型):
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
namespace Library.Models
{
public class Rental
{
public int Id { get; set; }
[Required]
public Customer Customer { get; set; }
[Required]
public Book Book { get; set; }
public DateTime DateRented { get; set; }
public DateTime? DateReturned { get; set; }
}
}
問題是-我想從數據庫中刪除RENTAL對象,但是在此之前,我想修改RENTAL對象內部的一個對象(Book)的值; 我想增加值“ NumberAvailable”。
書本類(型號):
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
namespace Library.Models
{
public class Book
{
public int Id { get; set; }
[Required]
[StringLength(255)]
public string Name { get; set; }
public Genre Genre { get; set; }
[Display(Name = "Kategoria")]
[Required]
public byte GenreId { get; set; }
public DateTime DateAdded { get; set; }
[Display(Name ="Data publikacji")]
public DateTime ReleaseDate { get; set; }
[Display(Name = "Ilosc w magazynie")]
[Range(1, 40)]
public byte NumberInStock { get; set; }
public byte NumberAvailable { get; set; }
}
}
可能嗎
謝謝你的幫助。
您正在嘗試使用與租金相同的ID來更改圖書。 您對書籍的查詢應使用rentalInDb.Book.Id。 這將為您提供需要修改的記錄。
嘗試這個:
book.NumberAvailable++;
_context.Books.Add(book);
_contextEntry(book).State = System.Data.Entity.EntityState.Modified;
_context.Rentals.Remove(rentalInDb);
_context.SaveChanges();
return Ok();
您需要將對象添加到已修改列表中,以保留在數據庫中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.