I'm loading an IQueryable of books from the Books table and there's another table named BookLoans. I have a DateTime? property in my ViewModel named Availability. I'm trying to figure out the best way to basically go out during my select statement and see if the current book's BookID shows up in a record within the BookLoans table and if a DateTime? variable named ReturnedWhen is also NULL in that record. I'm basically trying to mark the book as available or checked outed when I populate the the IQueryable.
It's been suggested that I try to do this all as one LINQ statement but I'm trying to figure out if it would be easier to just populate books like the following and then run it through a foreach loop? It's also been suggested that a Join would work but really I'm just trying to figure out the best method and then how to go about actually doing it.
var books =
_context.Books
.Select(r => new BookIndexViewModel
{
BookID = r.BookID,
Title = r.Title,
Author = r.Author,
ISBN = r.ISBN,
GenreName = r.Genre.Name
}).ToList();
Book Entity:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Open_School_Library.Data.Entities
{
public class Book
{
public int BookID { get; set; }
public string Title { get; set; }
public string SubTitle { get; set; }
public string Author { get; set; }
public int GenreID { get; set; }
public int DeweyID { get; set; }
public int ISBN { get; set; }
public Genre Genre { get; set; }
public Dewey Dewey { get; set; }
public virtual BookLoan BookLoan { get; set; }
}
}
BookLoan Entity:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Open_School_Library.Data.Entities
{
public class BookLoan
{
public int BookLoanID { get; set; }
public int BookID { get; set; }
public int StudentID { get; set; }
public DateTime CheckedOutWhen { get; set; }
public DateTime DueWhen { get; set; }
public DateTime? ReturnedWhen { get; set; }
public Book Book { get; set; }
public Student Student { get; set; }
}
}
BookIndexViewModel:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
namespace Open_School_Library.Models.BookViewModels
{
public class BookIndexViewModel
{
public int BookID { get; set; }
public string Title { get; set; }
[Display(Name = "Author")]
public string Author { get; set; }
[Display(Name = "Genre")]
public string GenreName { get; set; }
public int ISBN { get; set; }
public string BookLoan { get; set; }
public DateTime? Availability { get; set; }
}
}