EFCore, many-to-many, DB First, navigation properties not working

Viewed 307

I am trying to map to an existing database. When I use the below code and pull a list of results for a given entity, I get back the results I expect.

However, when I attempt to add .Include(x => x.Book) to a simple list query against the UserBook table, my result set returns empty.

[Table("User")]
public class User
{
    [Key]
    public Guid UserId { get; set; }
    public string UserName{ get; set; }

    // Reference
    public ICollection<UserBook> UserBooks { get; set; }
}

[Table("Book")]
public class Book
{
    [Key]
    public Guid BookId { get; set; }
    public string BookName{ get; set; }

    // Reference
    public ICollection<UserBook> UserBooks { get; set; }
}

[Table("UserBook")]
public class UserBook
{
    public Guid UserId { get; set; }
    public Guid BookId { get; set; }
    public int PermissionMask { get; set; }
    public bool Deleted { get; set; }

    // Ref
    public User User { get; set; }
    public Book Book { get; set; }
}

I'm following the instructions layed out here: http://www.learnentityframeworkcore.com/configuration/many-to-many-relationship-configuration

To better illustrate the issue, here are the queries I'm using:

// Returns 1,000+ rows.
_context.UserBooks.ToList();

// Returns 1 row
_context.UserBooks
    .Where(x => x.UserId == "SomeGuid")
    .ToList();

// Returns 0 rows
_context.UserBooks
    .Include(x => x.Book)
    .Where(x => x.UserId == "SomeGuid")
    .ToList();

// Returns 0 rows
_context.UserBooks.Include(x => x.Book).ToList();
2 Answers
Related