A.Mills
A.Mills

Reputation: 407

EF Core, object not able to reference other objects

I have a tree like structure. This tree has Nodes. Every object in my project has the ability to link to one of these nodes. However when I query using LINQ for an object it is unable to return that referenced nodes data.

public async Task<NodeModel> FindByID(string pID, CancellationToken pCancellationToken)
{
    pCancellationToken.ThrowIfCancellationRequested();
    return await Context.Nodes.FirstOrDefaultAsync(m => m.ID == pID);
}

Above is how I query the context for a single object based on ID. The photo below shows that its returning null.

enter image description here

For some Clarity. B is a child of A.
When I query the list like so

mContext.Nodes.ToList();

I the query is able to link the nodes?

What is going on here?

enter image description here

Upvotes: 0

Views: 61

Answers (1)

Chris Terry
Chris Terry

Reputation: 161

I think this is because you have lazily loaded navigation properties.

Try altering your query like this

public async Task<NodeModel> FindByID(string pID, CancellationToken pCancellationToken)
{
        pCancellationToken.ThrowIfCancellationRequested();
        return await Context.Nodes.Include(m => m.Node).FirstOrDefaultAsync(m => m.ID == pID);

}

The reason is works when you query all of the records is that Entity Framework is smart enough to know that it already has that entity loaded. Because you're querying the full data set in that case, the nodes are already loaded.

Upvotes: 3

Related Questions