How do you display values from a table based on an

2019-06-04 06:28发布

问题:

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...

My models are:

[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.

回答1:

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);
}