I am attempting to setup a relationship between two tables in EF Core.
Transaction and Transaction Classes.
A transaction may be assigned to a single Transaction Class - and a single transaction class may belong to different transactions.
Below is my attempt to set up a one to many relationship in the two model classes.
public class Transaction
{
public int TransactionId { get; set; }
public TransactionClass TransactionClass { get; set; }
}
public class TransactionClass
{
public int TransactionClassId { get; set; }
public string Class { get; set; }
public decimal Percentage { get; set; }
}
In the Database, the table structures match the above. The Transaction table also has a foreign key on TransactionClassId referencing TransactionClasses.TransactionClassId:
Both tables are populated and valid IDs are present on both the primary and foreign keys.
However, when I do the following:
using (accountingContext db = new())
{
foreach (Transaction transaction in db.Transactions)
{
System.Diagnostics.Debug.WriteLine(transaction.TransactionClass.Percentage);
}
}
I get the run time error:
System.NullReferenceException: 'Object reference not set to an instance of an object.'
WebApi.Models.Transaction.TransactionClass.get returned null.
I cannot see where I am going wrong here. All the online materials I have followed implement it in the same fashion as above.