0

I am attemptiong to fetch some entities from my DB which map to their respective EF Core models, but I am experiencing some difficulties with foreign tables:

Models/accountingContext.cs

namespace WebApi.Models
{
    public class accountingContext : DbContext
    {
        public DbSet<TransactionClass>? TransactionClasses { get; set; }
        public DbSet<TransactionType>? TransactionTypes { get; set; }

    }
}

Models/TransactionClass.cs

namespace WebApi.Models
{
    public class TransactionClass
    {
        public int TransactionClassId { get; set; } = 0;

        [ForeignKey("TransactionTypeId")]
        public int TransactionTypeId { get; set; };
        public TransactionType TransactionType { get; set; }
    }
}

Models/TransactionType.cs

namespace WebApi.Models
{
    public class TransactionType
    {
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int TransactionTypeId { get; set; }
        public string Type { get; set; }
        [InverseProperty("TransactionType")]
        public ICollection<TransactionClass> TransactionClasses { get; set; }
    }
}

The intention in the models above is to have the TransactionType table related to the TransactionClass table. In the DB itself I have also created a foreign key relationship linking TransactionClass.TransactionTypeId or TransactionType.TransactionTypeId.

When I then fetch all classes in the app as follows, the related TransactionClass.TransactionType property is always null instead of the related entity:

using (accountingContext db = new())
{
    return db.TransactionClasses.ToList();
}

I must be missing something above but I cannot see what it is.

Svyatoslav Danyliv
  • 21,911
  • 3
  • 16
  • 32
Musaffar Patel
  • 905
  • 11
  • 26
  • Does this answer your question? [Lazy Loading vs Eager Loading](https://stackoverflow.com/questions/31366236/lazy-loading-vs-eager-loading) – Felix Dec 26 '22 at 13:06
  • @Felix reading the post you referenced I get the impresssion I should use Eager loading for my situation. However my problem is that I cannot get the related entity in my result set at all – Musaffar Patel Dec 26 '22 at 13:12
  • 4
    First, you have to read up on Lazy vs. Eager loading. There are millions of articles on the topic. Second, they way you invoke `ToList()`, it *won't* load related classes unless you explicitly call `Include()`. Another (I consider better) way is to create a DTO that explicitly defines the shape of result object – Felix Dec 26 '22 at 13:16
  • @Felix I was missing the call to Include() ... new to EF so assumed it would be automatically populated. Thanks – Musaffar Patel Dec 26 '22 at 13:19

0 Answers0