繁体   English   中英

如何在删除对象内修改对象的值? [MVC,JSON,JavaScript]

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM