Get value from an entity via navigation property

0

I have a question that seems basic, but I'm breaking my head to solve.

How can I get the value of an attribute of an entity via Properties Navigations?

For example, I have the classes:

public class Budget
{
    public Guid Id {get; set;}
    ... // Outros atributos

    //Propriedade de Relacionamento
    public IEnumerable<BudgetItem> BudgetItems {get; set;}
}

public class BudgetItem
{
    public Guid Id {get; set;}
    public string NameItem {get; set;}
    ... // Outros atributos

    //ForeingKey
    public Guid BudgetId {get; set;}

    //Propriedade de Navegação
    public Budget Budget {get; set;}
}

In my Infra layer I have all the mapping. It works perfect. The CRUD is performed as expected and in this case, only the "Ids" of the entity are persisted in the bank. Nothing out of the ordinary. It turns out, I want to show in my View > Index a list of BudgetItem , each of which is related to a Budget .

The normal query looks like this:

Table in the View

BudgetItem | Budget ( Note: Guid saved is displayed )
Item 1 | a6fa353b-e55b-42f3-92f2-17cecda4725d
Item 2 | c7b90b8e-4fd1-4422-8c11-bb5fbaae7f05

What I need is to show it this way:

BudgetItem | Budget
Item 1 | Budget Name
Item 2 | Budget Name

In other applications (EF6 and Windows Forms) I just loaded doing a simple type query:

public IEnumerable<BudgetItem> GetByBudgetName(budgetName)
{
   return _context.ButgetItem.Where(c => c.Budget.Name.Equals(budgetName));
}

However, in ASP.NET Core 2.0 this does not work. I simply can not access data from another class / table through the navigation properties.

Follow my View:

<table class="table table-striped table-bordered table-hover">
  <thead>
    <tr>
      <th>@Html.DisplayNameFor(model => model.BudgetItem)</th>
      <th>@Html.DisplayNameFor(model => model.BudgetId)</th>
      <th>@Html.DisplayNameFor(model => model.Value)</th>
      <th></th>
    </tr>
  </thead>
  <tbody>
    @foreach (var item in(IEnumerable
    <BudgetItemViewModel>)ViewBag.ListBudget) {
      <tr>
        <td>@Html.DisplayFor(modelItem => item.Month)</td>        
        <td>@Html.DisplayFor(modelItem => item.BudgetId)</td>
        <td>@Html.DisplayFor(modelItem => item.Value)</td>
      </tr>
      }
  </tbody>
</table>

I need to replace the line <td>@Html.DisplayFor(modelItem => item.BudgetId)</td> so that instead of showing the "Id" show the description (name) of the corresponding Budget.

Since this is an FK, in my class I have the Navigation Property for it. So I thought it would work like this <td>@Html.DisplayFor(modelItem => item.Budget.Name)</td> .

Can noble friends help me with this?
Thanks in advance.

    
asked by anonymous 17.10.2018 / 21:38

0 answers