EntityFrameworkCore - many-to-many nie działa

0

Próbuję zmapować sobie relację wiele do wielu wg tego tutoriala:

Mam takie klasy:

 public class User
 {
        public Guid Id { get; protected set; }
        public IList<UserRole> UserRoles { get; set; }
        public User()
        {
        }
}

 public class Role
    {
        public Guid Id { get; set; }
        public string Name { get; set; }
        public IList<UserRole> UserRoles { get; set; }
        public Role()
        {
            
        }
    }

public class UserRole
    {
        public Guid UserId { get; set; }
        public User User { get; set; }

        public Guid RoleId { get; set; }
        public Role Role { get; set; }
    }

Dodałem mapowanie:


            modelBuilder.Entity<UserRole>()
                        .HasKey(ur => new { ur.UserId, ur.RoleId });

            modelBuilder.Entity<UserRole>()
                .HasOne(ur => ur.User)
                .WithMany(u => u.UserRoles)
                .HasForeignKey(ur => ur.UserId);

            modelBuilder.Entity<UserRole>()
                .HasOne(ur => ur.Role)
                .WithMany(r => r.UserRoles)
                .HasForeignKey(ur => ur.RoleId);

i teraz przy wyciąganiu z bazy:

var userRole = _dbContext.UserRoles.First();
var user = _dbContext.Users.First();

a) Obiekt userRole ma poprawnie wypełnione pola RoleId i UserId ale pola User i Role są null.
b) Obiekt user ma pole UserRoles równe null.

Co robię źle?

1

Masz kilka metod na to: Eager, Explicit albo Lazy.

https://docs.microsoft.com/en-us/ef/core/querying/related-data

0

Dzięki!
W tym wypadku interesuje mnie EagerLoading i tu pojawia się kolejne pytanie:

var user =  _dbContext.Users.Include(u => u.UserRoles).First();

I faktycznie user ma już UserRoles. Z kolei w tej kolekcji elementy UserRole mają np Role równe null.
To jeśli mam takiego pojączka to w EF muszę tych includów narzeźbić na tyle głęboko ile danych chce zaciągnąć?

W porównaniu z NHibernatem to trochę mało wygodne.

1

Tak, musisz określić które tabelę chcesz JOINować

Użyj ThenInclude

1 użytkowników online, w tym zalogowanych: 0, gości: 1