Jamiec
Jamiec

Reputation: 136124

Using the Include Method to load related objects in EntityFramework

Below is a section of my Entity Framework Model. You'll notice I have a "header" table, which is related to many "AssetHolding" records, which itself can be one of 3 types - for which im using inheritance (TpH). Please ignore the fact that all 3 inherited types look identical - this is intentional

Entity model

When editing this data, I need to pull one specific header by Id, and all associated AssetHoldings. The method to do so looks like this:

public AssetValuationHeader GetValuationHeaderById(int id)
{
    return this.AssetValuationHeaders
        .Include("AssetHoldings")
        .Where(vh => vh.Id == id)
        .FirstOrDefault();
}

This correctly loads everything highlighted with a red border in the image above.

The problem im having is that I also need to load the bit highlighted with a green border in the above image. As you can see this is only related off of one of the 3 inheritance tables.

I tried this:

public AssetValuationHeader GetValuationHeaderById(int id)
{
    return this.AssetValuationHeaders
        .Include("AssetHoldings")
        .Include("AssetHoldings.SwapAssetHoldingNotionals")
        .Where(vh => vh.Id == id)
        .FirstOrDefault();
}

A specified Include path is not valid. The EntityType 'CoreValuationModel.AssetHolding' does not declare a navigation property with the name 'SwapAssetHoldingNotionals'.

Is this even possible using the Include method? (ie, without using LazyLoading) Any workaround if not?

Upvotes: 2

Views: 1904

Answers (1)

jim tollan
jim tollan

Reputation: 22485

jamie,

[spoiler] - this is coded from complete memory and may not actually compile at all!!

Anyway, I've had situations where I've had to load the graph a few levels deep and seem to remember doing something along the following lines:

public AssetValuationHeader GetValuationHeaderById(int id)
{
    return this.AssetValuationHeaders
        .Include("AssetHoldings")
        .Include("AssetHoldings").Select(sa => sa.SwapAssetHoldingNotionals)
        .Where(vh => vh.Id == id)
        .FirstOrDefault();
}

or:

public AssetValuationHeader GetValuationHeaderById(int id)
{
    return this.AssetValuationHeaders
        .Include("AssetHoldings")
        .Include("AssetHoldings").Include("SwapAssetHoldingNotionals")
        .Where(vh => vh.Id == id)
        .FirstOrDefault();
}

as i said, don't shoot the messenger (will check this out away from my 'phone' later)

Upvotes: 1

Related Questions