PIbd-22_Rogashova_E.A._SUBD/BookShop/Models/Book.cs

105 lines
3.6 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using BookShopContracts.BindingModels;
using BookShopContracts.ViewModels;
using BookShopDataModels.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;
namespace BookShopDataBaseImplement.Models
{
public class Book : IBookModel
{
public int Id { get; private set; }
[Required]
public string BookName { get; set; } = string.Empty;
[Required]
public int Count { get; set; }
[Required]
public double Cost { get; set; }
[Required]
public int GenreId { get; set; }
private Dictionary<int, (IAuthorModel, int)>? _bookAuthors = null;
[NotMapped]
public Dictionary<int, (IAuthorModel, int)> BookAuthors
{
get
{
if (_bookAuthors == null)
{
_bookAuthors = Authors
.ToDictionary(recPC => recPC.AuthorId, recPC =>
(recPC.Author as IAuthorModel, recPC.Count));
}
return _bookAuthors;
}
}
[ForeignKey("BookId")]
public virtual List<BookAuthor> Authors { get; set; } = new();
[ForeignKey("BookId")]
public virtual List<Order> Orders { get; set; } = new();
public static Book Create(BookShopDatabase context, BookBindingModel model)
{
return new Book()
{
Id = model.Id,
BookName = model.BookName,
Cost = model.Cost,
Count = model.Count,
Authors = model.BookAuthors.Select(x => new BookAuthor
{
Author = context.Authors.First(y => y.Id == x.Key),
Count = x.Value.Item2
}).ToList()
};
}
public void Update(BookBindingModel model)
{
BookName = model.BookName;
Cost = model.Cost;
}
public BookViewModel GetViewModel => new()
{
Id = Id,
BookName = BookName,
Cost = Cost,
BookAuthors = BookAuthors
};
public void UpdateAuthors(BookShopDatabase context, BookBindingModel model)
{
var bookAuthors = context.BookAuthors.Where(rec =>
rec.BookId == model.Id).ToList();
if (bookAuthors != null && bookAuthors.Count > 0)
{ // удалили те, которых нет в модели
context.BookAuthors.RemoveRange(bookAuthors.Where(rec
=> !model.BookAuthors.ContainsKey(rec.AuthorId)));
context.SaveChanges();
// обновили количество у существующих записей
foreach (var updateAuthor in bookAuthors)
{
updateAuthor.Count = model.BookAuthors[updateAuthor.AuthorId].Item2;
model.BookAuthors.Remove(updateAuthor.AuthorId);
}
context.SaveChanges();
}
var book = context.Books.First(x => x.Id == Id);
foreach (var pc in model.BookAuthors)
{
context.BookAuthors.Add(new BookAuthor
{
Book = book,
Author = context.Authors.First(x => x.Id == pc.Key),
Count = pc.Value.Item2
});
context.SaveChanges();
}
_bookAuthors = null;
}
}
}