I have this model:
[Table("Book")]
public class Book
{
[Key]
public int BookID {get; set;}
[Column("Title")]
public string Title {get; set;}
// The IsReaded column must store a Boolean value relative to the current (authorized) user.
[NotMapped]
public bool IsReaded {get; set;}
}
The data about what is authorized by the user I receive using the IdentityModel
, User.Identity.GetUserId ()
function.
Data on whether the user has read the book or not is in the following model (table):
[Table("Readers")]
public class Reader
{
[Key]
public int UserId {get; set;}
[ForeignKey("BookId")]
public int BookId {get; set;}
}
If in this table there is data about the user and the book he read, it means that he read it.
I found a way to do this through the repository, describing the GetBook method in which I would additionally assign a value to the IsReaded field. (https://www.asp.net/mvc/overview/older-versions/getting-started-with-ef-5-using-mvc-4/implementing-the-repository-and-unit-of-work-patterns-in-an-asp-net-mvc-application)
But in my project the Book model will be used very often, in different places I use the methods: skip, take, where and others. And the code turns out a bit awkward:
public Book GetBook(int booked){
var book = db.Books.SingeOrDefault(x=>x.BookId==booked);
book.IsReaded = db.Readers.Any(x=>x.BookId==booked && x.UserId == User.Identity.GetUserId());
return book;
}
public Book GetBooks(){
var books = db.Books.ToList();
var results = new List<Book>();
foreach(var item in books){
var book = new Book();
book.IsReaded = db.Readers.Any(x=>x.BookId== item.BookId && x.UserId == User.Identity.GetUserId());
results.add(book);
}
return results.add;
}
But here is one of the problems when I have for example such a method:
var query = bookRepo.GetBooks().Where(x => x.Title != "NO").OrderByDescending(x => x.Title);
var part = new BookParts()
{
TotalItems = query.Count(),
Books = query.Skip(5).Take(10).ToList()
};
It looks very nice to create queries to the database through the secondary contexts in the model. But it is very slow and there is no need to create additional contexts for each model.
[NotMapped]
public book IsReaded {
get {
var activeUserId = HttpContext.Current.User.Identity.GetUserId();
using (ContextDb db = new ContextDb())
{
if (activeUserId != null)
{
return db.Readers.Any(x=>x.UserId == activeUserId && x.BookId==BookId)
}
}
}
}
I do not know how best, helpful advice? How to do it better? I searched the Internet and found nothing useful for me. I hope for help!