Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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();
like image 667
Daniel Brown Avatar asked Nov 24 '25 23:11

Daniel Brown


1 Answers

I think EF would complain that UserBook entity does not have keys defined, not sure how you got it to work. But to make the include work I believe you need to be explicit on the composite key. Try adding the following to your DbContext class:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    base.OnModelCreating(modelBuilder);
    modelBuilder.Entity<UserBook>(e => e.HasKey(c => new { c.UserId, c.BookId }));
}
like image 164
Alaa Masoud Avatar answered Nov 26 '25 12:11

Alaa Masoud



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!