簡體   English   中英

EF核心:更新一對多關系相關實體ID

[英]EF Core: Updating One-to-Many Relationship dependent entity id

我是ASP.NET核心和EF核心的新手。 請檢查我的代碼,讓我知道我在做什么錯。

** AuthorId違反外鍵約束。 **無法跟蹤BookCategory實體,因為正在跟蹤具有相同ID的另一個實例

書本模型

public class Book
    {
        public int BookId { get; set; }
        public string Title { get; set; }
        public double Price { get; set; }
        public int? Discount { get; set; }
        public string ImagePath { get; set; }
        public int? Stock { get; set; }

        public Author Author { get; set; }
        public int AuthorId { get; set; }

        public BookCategory Category { get; set; }
        public int? CategoryId { get; set; }

        public ICollection<JoinBookTag> BookTags { get; set; }
    }

BookCategory模型

public class BookCategory
    {
        public int Id { get; set; }

        [Display(Name = "Category Name")]
        public string CategoryName { get; set; }

        public ICollection<Book> Books { get; set; }

    }

作者模型

public class Author
    {
        public int AuthorId { get; set; }
        public string Name { get; set; }

        public ICollection<Book> Books { get; set; }
    }

BookController

        private readonly ApplicationDbContext _db;
        private readonly HostingEnvironment _hostingEnvironment;


        [BindProperty]
        public BookViewModel ViewModel { get; set; }
        public BookController(ApplicationDbContext db, HostingEnvironment host)
        {
            _db = db;
            _hostingEnvironment = host;
            ViewModel = new BookViewModel()
            {
                Book = new Models.Book(),
                Authors = _db.Authors.ToList(),
                BookCategories = _db.BookCategories.ToList(),
                Tags = _db.Tags.ToList()
            };
        }

......

[HttpGet]
        public IActionResult Edit(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }
            var book = _db.Books.Include(b => b.Category)
                        .Include(b => b.Author)
                        .SingleOrDefault(b => b.BookId == id);
            if (book == null)
            {
                return NotFound();
            }
            ViewModel.Book = book;
            return View(ViewModel);
        }

[HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Edit(BookViewModel model, int? id)
        {
            if (id == null)
            {
                return NotFound();
            }
            if (id != model.Book.BookId)
            {
                return NotFound();
            }
            if (!ModelState.IsValid)
            {
                /*ViewModel.Book = model.Book;
                return View(ViewModel);*/
                var errors = ModelState.Select(x => x.Value.Errors)
                           .Where(y => y.Count > 0)
                           .ToList();
                return Json(new { errors });
            }
            var dbModel = _db.Books.Include(b => b.Category).Where(b => b.BookId == id).FirstOrDefault();

            var file = HttpContext.Request.Form.Files;
            if (file.Count > 0)
            {
                var RootDirectory = _hostingEnvironment.WebRootPath;
                var extension = Path.GetExtension(file[0].FileName);
                var filePath = Path.Combine(DataContext.ImageDirectory, model.Book.BookId + extension);
                using (var fileStream = new FileStream(Path.Combine(RootDirectory, filePath), FileMode.Create))
                {
                    file[0].CopyTo(fileStream);
                }

                dbModel.ImagePath = @"/" + filePath;
            }
            dbModel.AuthorId = model.Book.AuthorId;
            dbModel.CategoryId = model.Book.CategoryId;
            dbModel.Discount = model.Book.Discount;
            dbModel.Price = model.Book.Price;
            dbModel.Stock = model.Book.Stock;
            dbModel.Title = model.Book.Title;

            await _db.SaveChangesAsync();
            return RedirectToAction(nameof(Index));

        }

您需要在模型內的id屬性上添加key屬性。

接下來需要更新的是告訴_db然后先更新您的實體,然后才保存更改。

為什么要使用異步並等待? 這些控制器動作會減慢UI速度嗎?

您還可以發布您的書本瀏覽模型嗎?

您的操作方法在某些地方是錯誤的。 如果您需要更詳細的建議,請告訴我。

    [HttpGet]
    public IActionResult Edit(int? id)
    { 
       //Give this a name other than view model for example BookViewModel
       ViewModel model = new ViewModel();

        if (id == null)
        {
            return NotFound();
        }

        var book = _db.Books.Include(b => b.Category)
                    .Include(b => b.Author)
                    .SingleOrDefault(b => b.BookId == id);

        if (book == null)
        {
            return NotFound();
        }

        model.Book = book;

        return View(model);
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> Edit(BookViewModel model, int? id)
    {
        if (id == null || id != model.Book.BookId)
        {
            return NotFound();
        }

        if (ModelState.IsValid)
        {
            var dbModel = _db.Books.Include(b => b.Category).Where(b => b.BookId == id).FirstOrDefault();

        var files = HttpContext.Request.Form.Files;
        if (files.Any())
        {
            var RootDirectory = _hostingEnvironment.WebRootPath;
            var extension = Path.GetExtension(files[0].FileName);
            var filePath = Path.Combine(DataContext.ImageDirectory, model.Book.BookId + extension);
            using (var fileStream = new FileStream(Path.Combine(RootDirectory, filePath), FileMode.Create))
            {
                file[0].CopyTo(fileStream);
            }

            dbModel.ImagePath = @"/" + filePath;
        }

        dbModel.AuthorId = model.Book.AuthorId;
        dbModel.CategoryId = model.Book.CategoryId;
        dbModel.Discount = model.Book.Discount;
        dbModel.Price = model.Book.Price;
        dbModel.Stock = model.Book.Stock;
        dbModel.Title = model.Book.Title;

        await _db.Books.UpdateAsync(dbModel);
        await _db.SaveChangesAsync();

        return RedirectToAction(nameof(Index));

        }

        return View(model);

    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM