I'm working on a simple project where I have data in two tables that I need to return to my View from my controller. I'm aware of two methods to do this in .NET, the first is create a model class, add the properties you need to access in your view, essentially creating a ViewModel. Like so:
public class BeerListViewModel
{
public int Id { get; set; }
public string Name { get; set; }
public string BrewerName { get; set; }
public string City { get; set; }
public string Country { get; set; }
public string WebUrl { get; set; }
public string ImageUrl { get; set; }
public double AlcoholContent { get; set; }
public string BeerType { get; set; }
public int Calories { get; set; }
public double Carbs { get; set; }
public string Notes { get; set; }
public int CountofReviews { get; set; }
}
Then set your model to a LINQ statement selecting the DbSet and instantiating the ViewModel and load it with the properties you need to send to the view, then return your model to the View, Like so:
//1. Instantiate the db
OdeToBeerDb _db = new OdeToBeerDb();
// GET: Reviews
public ActionResult Index()
{
var model = from b in _db.Beers
orderby b.Name ascending
select new BeerListViewModel
{
Id = b.Id,
Name = b.Name,
BrewerName = b.BrewerName,
BeerType = b.BeerType,
ImageUrl = b.ImageUrl,
City = b.City,
Notes = b.Notes,
AlcoholContent = b.AlcoholContent
};
return View(model);
}
With the other method, you simply join the two tables in the LINQ query, select the properties you need to send to the View in the anonymous object and return the view, like so:
public class ReviewsController : Controller
{
//1. Instantiate the db
OdeToBeerDb _db = new OdeToBeerDb();
// GET: Reviews
public ActionResult Index()
{
var model = from b in _db.Beers
join r in _db.Reviews on b.Id equals r.BeerId
orderby b.Name ascending
select new
{
Id = b.Id,
Name = b.Name,
BrewerName = b.BrewerName,
BeerType = b.BeerType,
ImageUrl = b.ImageUrl,
City = b.City,
Notes = b.Notes,
AlcoholContent = b.AlcoholContent
};
return View(model);
}
What I'm wondering is: Why would I bother creating a ViewModel, copying and pasting the properties from my other classes into it, and instantiating the ViewModel? It seems kind of redundant to do that vs. just joining the tables, or is there some advantage that I am missing? And yes, I know that it is strongly typed and creating the ViewModel names the object but I have to add the properites to that class anyway, so what difference does it make if I add them to the class or the controller? For that matter, is there some equivalent to SELECT *
in LINQ? Then, I wouldn't have to add the properties to the controller every time I change my model.