Sergio Di Fiore
Sergio Di Fiore

Reputation: 466

Retrieve inner database field in a foreach with entity framework

I have a "Finalidade" table which is son of the "Insumo" table.

In the following code:

var db = new ApplicationDbContext();
var model = db.Insumos;

foreach (var register in model)
{
    data.Custo = register.Finalidade.Descricao == "Revenda"
        ? data.Custo
        : data.Custo - data.CrdtIpi;
}

I need to retrieve the value of the inner field "Finalidade.Descricao" so that I can compare to my string. The problem is, as it is son of Insumo the whole thing come as null and my program won't work.

As I don't have how to use "Include" with "register" I'm not able to retrieve the value I need.

How can I retrieve the value of "register.Finalidade.Descricao"?

Upvotes: 1

Views: 217

Answers (1)

Grizzly
Grizzly

Reputation: 5953

You do not use .Include() on the object named register. You can use it when you initialize the model property.

// .ToList is optional
var model = db.Insumos.Include(x => x.Finalidade).ToList();

You have to use eager loading to accomplish what you're trying to achieve.

Let me know if this helps!

Upvotes: 1

Related Questions