[英]Retrieve data from multiple tables in ASP.NET MVC using Entity Framework and a repository pattern
I have 2 classes related in my model: 我的模型中有2个相关的类:
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(); 公共类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. 我正在尝试使用Razor引擎加载产品及其提供程序名称以显示在页面中。 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
: 在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. 我需要一种导航到Provider
类的OfficialName
属性的方法,以便在视图中将其与Product
其他属性一起显示。
You should add a navigational property of type Provider
to your Product
class. 您应该将Provider
类型的导航属性添加到Product
类。
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 现在,您可以将产品列表传递到视图,并在视图中循环浏览时使用Product属性。
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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.