Send info to the view from another table with navigation property?

40 views Asked by At

This is my models

 public class Product
 {
    [Key]
    public int SerialNumber { get; set; }
    public int PartNumber { get; set; }
    public string Description { get; set; }

    public virtual ICollection<Reading> Reading { get; set; }
}

public class Reading
{
    [Key]
    public int Id { get; set; }
    public int SerialNumber { get; set; }
    public int ReadingValue { get; set; }
    public virtual Product Product { get; set; }
}

I can send all products to the view with

   return View(db.Products.ToList().Where(product => product.CustomerID == Customer));

And I can get the latest ReadingValue if I know the Product SerialNumber

        var LatestReading = db.Readings.OrderByDescending(m => m.Id).Where(s => s.SerialNumber == SerialNumber).Select(m => m.ReadingValue).FirstOrDefault();

How can I send all the products to the view with the latest ReadingValue for each product?

2

There are 2 answers

0
hutchonoid On

Create a new view model that will hold both the data:

public class FooViewModel
{
    public List<Product> Products { get; set; }
    public Reading LatestReading { get; set; }
}

Change your view to use the new model with:

@model FooViewModel

Then send them back in your controller:

var model = new FooViewModel();
model.Products = db.Products.ToList().Where(product => product.CustomerID == Customer);
model.LatestReading =  db.Readings.OrderByDescending(m => m.Id).Where(s => s.SerialNumber == SerialNumber).Select(m => m.ReadingValue).FirstOrDefault();

return View(model);
0
Alex Sikilinda On

Because you have Reading property in Products class, you can get the latest ReadingValue in the view:

foreach(Product product in Model)
{
    var latestReadingValue = product.Reading.OrderByDescendin(m => m.Id).FirstOrDefault();
    // do what you want here 
}

but as hutchonoid points out the better option is creating a ViewModel for it, because having logic in the view is a bad practice, and it doesn't correspond to MVC pattern.