繁体   English   中英

使用实体框架和存储库模式从ASP.NET MVC中的多个表中检索数据

[英]Retrieve data from multiple tables in ASP.NET MVC using Entity Framework and a repository pattern

我的模型中有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; }
}

公共类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               
}

我正在尝试使用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其他属性一起显示。

您应该将Provider类型的导航属性添加到Product类。

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>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM