❔ EntityFramework Relations doesn't work

Hewoo, I'm new to EntityFramework and I'm trying to make a simple One to Many relation but it doesn't work
13 Replies
Harley Sky Saphri
This is how to models looks like
Harley Sky Saphri
When I try to load the data the Numbers field in contact is null, but the data exists in the database
Harley Sky Saphri
the error
Harley Sky Saphri
public class ContactContext : DbContext
{
public DbSet<Contact> Contacts { get; set; }

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlite("Data Source=./database.sqlite");
}
}
public class ContactContext : DbContext
{
public DbSet<Contact> Contacts { get; set; }

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlite("Data Source=./database.sqlite");
}
}
that's the ContactContext class what am I missing here to make the relation work?
Saber
Saber3y ago
when querying for an entity, the relationships are not loaded unless you include them. https://learn.microsoft.com/en-us/ef/core/querying/related-data/eager
Eager Loading of Related Data - EF Core
Eager loading of related data with Entity Framework Core
Harley Sky Saphri
Ooo 👀 I will read it
Harley Sky Saphri
for some reason its searching for a table called PhoneNumbers but the correct name would be PhoneNumber (without the S)
Harley Sky Saphri
do I need to rename the model class?
SuperBrain
SuperBrain3y ago
You forgot to declare a DbSet for PhoneNumbers
Harley Sky Saphri
Oooo
SuperBrain
SuperBrain3y ago
It is a standard EF convention to pluralize table names while keeping your entity names in singular form.
Harley Sky Saphri
public DbSet<PhoneNumber> PhoneNumber { get; set; }
public DbSet<PhoneNumber> PhoneNumber { get; set; }
after adding this line to the Context everything is working as intended! thanks Ooo 👀
Accord
Accord3y ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.

Did you find this page helpful?