在ASP中检索多个表中的数据.使用实体框架和存储库模式的.NET MVC
本文关键字:框架 存储 模式 MVC NET 实体 检索 ASP 数据 | 更新日期: 2023-09-27 18:06:39
我的模型中有两个相关的类:
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; }
}
和
公共类提供程序{公共提供者(){这一点。product = 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
}
我试图加载产品与它的提供商名称一起显示在使用Razor引擎的页面。比如:
Product Name (from table A) | Provider Name (from table B)
Soft drink | Coca-Cola
Chips | Lays
检索ProductsRepository
类产品的方法:
public ICollection<Product> ReadAll()
{
return context.Products.ToList();
}
我需要一种方法来导航到Provider
类的OfficialName
属性,以便在视图中显示它与Product
的另一个属性。
你应该给你的Product
类添加一个类型为Provider
的导航属性。
public class Product
{
// Your existing properties goes here
public int ProviderID { get; set; }
public Provider Provider { set;get;}
}
现在您可以将产品列表传递给视图,并在视图
中循环使用Product属性。public ActionResult Items()
{
var data = yourDbContext.Products.ToList();
return View(data);
}
现在,在视图
@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>