I have 2 classes related in my model:
public class Product
{
public Product()
{
this.Additives = new HashSet<Additive>();
}
public int Id { get; set; }
public string Name { get; set; } // refrigerante
public string CommercialName { get; set; } // nome popular, ex: fanta laranja
public string Brand { get; set; } // marca, ex: Coca-cola
public string Details { get; set; } // composicao, ingredientes
public HalalState HalalState { get; set; } // estado: halal, haram ou desconhecido
public DateTime? LastUpdate { get; set; } // date e hora do registo
public ICollection<Additive> Additives { get; set; } // aditivos
public int ProviderID { get; set; }
}
and
public class Provider { public Provider() { this.Products = new HashSet(); }
public int ProviderId { get; set; }
public string OfficialName { get; set; } // nome usado no licenciamento
public string PopularName { get; set; } // nome popular, mais conhecido
public int Nuit { get; set; } //identificacao tributaria
public EstablishmentCategory EstablishmentCategory { get; set; } // tipo de estabelecimento
public HalalState HalalState { get; set; }
public DateTime? LastUpdate { get; set; } // date e hora do registo
public ICollection<Product> Products { get; set; } // lista de produtos halal
}
I'm trying to load products alongside with its provider name to display in page using Razor engine. Something like:
Product Name (from table A) | Provider Name (from table B)
Soft drink | Coca-Cola
Chips | Lays
The method to retrieve products in class ProductsRepository
:
public ICollection<Product> ReadAll()
{
return context.Products.ToList();
}
I need a way to navigate to OfficialName
property of the Provider
class, in order to display it alongside another properties of Product
in a view.
You should add a navigational property of type Provider
to your Product
class.
public class Product
{
// Your existing properties goes here
public int ProviderID { get; set; }
public Provider Provider { set;get;}
}
Now you can pass a list of Products to the view and use the Product property when you loop through then in the view
public ActionResult Items()
{
var data = yourDbContext.Products.ToList();
return View(data);
}
Now, in the view
@model IEnumerable<Product>
<table>
<tr>
<th>Name</th>
<th>Provider</th>
</tr>
@foreach(var item in Model)
{
<tr><td>@item.Name</td><td>@item.Provider.OfficialName</td></tr>
}
</table>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.