Entity Framework Core always returns an empty list of foreign rows

asp.net-core entity-framework-core

Question

I'm working with Entity Framework Core and ASP.NET Core 3.1.

I have two simple models:

public class UserModel 
{
        public int    UserModelId   { get; set; }
        public string Email         { get; set; }
        public string Password      { get; set; }
        public string Name          { get; set; }
        public string Surname       { get; set; }
        public string Token         { get; set; }

        public List<TherapyModel> Therapies { get; set; }
}

public class TherapyModel 
{
        public int      TherapyModelId  { get; set; }
        public int      UserModelId     { get; set; }
        public string   Title           { get; set; }
        public int      Quantity        { get; set; }
        public bool     Monday          { get; set; }
        public bool     Tuesday         { get; set; }
        public bool     Wednesday       { get; set; }
        public bool     Thursday        { get; set; }
        public bool     Friday          { get; set; }
        public bool     Saturday        { get; set; }
        public bool     Sunday          { get; set; }
        public string   ImgBase64       { get; set; }
        public string   ImgUrl          { get; set; }

        public int UserModelForeignKey { get; set; }
        public UserModel UserModel           { get; set; }
}

Now, I initialize everything in this way:

public class DatabaseManager : DbContext 
{
        //Entities:
        public DbSet<UserModel>     UserModel    { get; set; }
        public DbSet<TherapyModel>  TherapyModel { get; set; }

        protected override void OnModelCreating( ModelBuilder modelBuilder ) 
        {
            modelBuilder.Entity<TherapyModel>().HasOne(p => p.UserModel)
                                               .WithMany(s => s.Therapies)
                                               .HasForeignKey(p => p.UserModelForeignKey);
        }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
            => optionsBuilder.UseMySql( @"Server=127.0.0.1;database=test2;uid=root;pwd=" ); );
}

The local db is populated correctly, with the right foreign keys. In fact this query returns 3 rows:

select * 
from usermodel 
join therapymodel on therapymodel.UserModelForeignKey 

But, for some reason, when I try to get the UserModel from my C# code, this always returns "Therapies" as NULL. I get to takes UserModel in this two way:

UserModel user = dbManager.UserModel.FirstOrDefault( user => user.UserModelId == iUserModel.UserModelId );

var users = dbManager.UserModel;

Both user and users had Therapies as NULL. I really can't understand why. Any help?

1
0
2/13/2020 4:14:06 PM

Accepted Answer

Ok I found finally an answer. By reading this post:

https://www.learnentityframeworkcore.com/lazy-loading

I enabled Lazy-Loading ( is enabled by default ) but the foreign key must be virtual:

public class Author
{
    public int AuthorId { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public virtual List<Book> Books { get; set; } = new List<Book>();
}
public class Book
{
    public int BookId { get; set; }
    public string Title { get; set; }
    public int AuthorId { get; set; }
    public virtual Author Author { get; set; }
}

Now it works, the Microsoft Tutorial don't tell you nothing about the Lazy Loading and the fact to declare the foreign key as virtual. I hope this could be help anyone in future.

0
2/13/2020 4:47:34 PM

Popular Answer

You need to eager load the Therapies, like this:

UserModel user = dbManager.UserModel.Where( user => user.UserModelId == iUserModel.UserModelId ).Include( user => user.Therapies ).SingleOrDefault();

Using SingleOrDefault because, as you are querying per primary key, there should be really at most only one record. See more here: https://docs.microsoft.com/en-us/ef/core/querying/related-data.



Related Questions





Related

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