你如何在MVC 4根据其它表的表中显示值? [英] How do you display values from a table based on another table in MVC 4?
问题描述
我有2个型号客户表和产品表。我是pretty新MVC和我创建了一个模型,我对细节的自动生成的控制器和视图,删除,创建...等...
I have 2 Models a customer table and a product table. I am pretty new to MVC and I have created a model and I have the auto generated controller and views for details, delete, create... etc...
我的型号是:
[Table("Product")]
public class Product
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int ProductId { get; set; }
public decimal Price { get; set; }
public int CustomerId { get; set; }
}
[Table("Customer")]
public class Customer
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int CustomerId { get; set; }
public string Name { get; set; }
}
我的问题是,我该如何显示基于客户名称的产品清单。显然,他们是由客户编号加入,但我怎么结合控制器。所以,我想根据从另一个表中的数据显示一些数据。
My question is, how do I display a list of the products based on the customer name. Obviously they are joined by CustomerId but how do I combine controllers. So I want to display some data based on data from another table.
推荐答案
您需要导航属性添加到客户。
You need to add a Navigation Property to Customer.
[Table("Customer")]
public class Customer
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int CustomerId { get; set; }
public string Name { get; set; }
public virtual ICollection<Product> Products { get; set; }
}
然后,你可以用它来访问该产品的客户。
Then you can use that to access the products for a customer.
public ActionResult ProductsByCustomer(string id)
{
// Find the customer by name
var customer = dbContext.Customer.First(c => c.Name == id);
// Get the customers products
var customersProducts = customer.Products;
// Send products to the View to be rendered
return View(customersProducts);
}
这篇关于你如何在MVC 4根据其它表的表中显示值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!