I created local database using EF core and code-first method. The db imitates library, so I have 3 simple tables: users, books and reservations.
Issue occurs when I want to get nested data like find one book and get its reservation. I think I should be able to use
List<Reservation> reservations = book.Reservations;
but I have to use
List<Reservation> reservations = libraryContext.Reservations.
Where(r=> r.Book == book).ToList();
But the main reason I need help is this fragment
BookReservationsModel bookReservationsModel = new BookReservationsModel
{
BookTitle = book.Title,
Reservations = reservations
};
// I want to display emails in View.
for (int i = 0; i < bookReservationsModel.Reservations.Count; i )
{
Debug.WriteLine(bookReservationsModel.Reservations[i].User.Email);
}
I cannot get access to users because they are nulls. In database everything is stored as it should be (correct ids). Of course I could copypaste certain emails to new created list but it's inefficient and I know I should be able to use it that way. I worked before with EF for Framework and I tried google the problem but couldn't find the solution.
Models and context code.
public class User
{
[Key]
public int UserID { get; set; }
[Required]
public string Name { get; set; }
[Required]
public string LastName { get; set; }
[Required]
public string Email { get; set; }
[Required]
public string Salt { get; set; }
[Required]
public string Password { get; set; }
public ICollection<Reservation> Reservations { get; set; }
}
public class Book
{
[Key]
public int BookID { get; set; }
[Required]
public string Title { get; set; }
[Required]
public string Author { get; set; }
[Required]
[DataType(DataType.Date)]
public DateTime PublishDate { get; set; }
[Required]
public string Description { get; set; }
public ICollection<Reservation> Reservations { get; set; }
}
public class Reservation
{
[Key]
public int ReservationID { get; set; }
[Required]
public DateTime ReservationDate { get; set; }
[Required]
public int UserID { get; set; }
[ForeignKey("UserID")]
public User User { get; set; }
[Required]
public int BookID { get; set; }
[ForeignKey("BookID")]
public Book Book { get; set; }
}
public class LibraryContext : DbContext
{
public LibraryContext(DbContextOptions options) : base(options) { }
public DbSet<User> Users { get; set; }
public DbSet<Book> Books { get; set; }
public DbSet<Reservation> Reservations { get; set; }
}
CodePudding user response:
Attempting to use a navigation property on the book
entity without doing either of the following will result in the property being null.
- Including the property before materializing the entity with
.First()
/.Single()
- Configuring EFCore to AutoInclude navigation properties by default.
I suggest when querying for the book
to use the Include and ThenInclude methods so the Reservations and Users are populated.
var book = await libraryContext.Books
.Include(x => x.Reservations)
.ThenInclude(x => x.User)
.SingleAsync(x => x.BookID == myBookId);