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.