Home > Mobile >  One to many relationship in EF Core fails
One to many relationship in EF Core fails

Time:09-26

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.

CodePudding user response:

EntityFramework does not automatically load any related entities to ones that you query. You need to .Include(x => x.OtherEntity) to instruct EF that it should load these.

An example, using your code:

using (accountingContext db = new())
{
    var transactions = db.Transactions
        .Include(x => x.TransactionClass)
        .ToList();

    foreach (var transaction in transactions)
        [...]
}

CodePudding user response:

public class Transaction
{
    public int TransactionId { get; set; }

    public IEnumerable<TransactionClass> TransactionClasses { get; set; }
}


public class TransactionClass
{
    public int TransactionClassId { get; set; }
    public string Class { get; set; }
    public decimal Percentage { get; set; }

    public int TransactionId { get; set; }
    public Transaction Transaction { get; set; }

}
  • Related