Entity framework core relationship collection is empty

c# ef-database-first entity-framework-core


I did do a database first approach, and I did make my database. I use relationship and I have two tables:

id PK int(11)
username UNIQUE varchar(20)

id PK int(11)
owner_id INDEX int(11) -> FK to users.id

When I do a scaffold, the models look a little like this:


public User()
    Rooms = new HashSet<Room>();

public int Id { get; set; }
public string Username { get; set; }
public virtual ICollection<Room> Rooms { get; set; }


public int Id { get; set; }
public string Name { get; set; }
public int? OwnerId { get; set; }

public virtual User Owner { get; set; }

(the OwnerId is nullable since system rooms don't have an assigned owner)

The problem is, if I have my user object obtained when logging in, and I view user.Rooms, the collection is always empty, even though the database has an entry.

I know include fixes this, but that makes me have to load ALL rooms from the database, which is a terrible idea when there's like 1000+ rooms being loaded on start of the program.

Why is the collection always empty even though the relationships are setup correctly?

5/31/2019 10:36:27 AM

Popular Answer

Setting up relationsips are different from loading related entities on memory. There are 4 different loading mechanisms you can choose according to your needs.

  1. Eager(Include and ThenInclude)
  2. Explicit
  3. Lazy Loading(EF Core 2.1)
  4. Select Loading

You can use select loading to filter which related entites must be loaded. So you do not need to load all related entitites.

5/31/2019 2:07:28 PM

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow