c# - LINQ in .NET MVC: Any advantage to creating a ViewModel vs. joining tables? -
i'm working on simple project have data in 2 tables need return view controller. i'm aware of 2 methods in .net, first create model class, add properties need access in view, creating viewmodel. 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 model linq statement selecting dbset , instantiating viewmodel , load properties need send view, return model view, so:
//1. instantiate db odetobeerdb _db = new odetobeerdb(); // get: reviews public actionresult index() { var model = 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 other method, join 2 tables in linq query, select properties need send view in anonymous object , return view, so:
public class reviewscontroller : controller { //1. instantiate db odetobeerdb _db = new odetobeerdb(); // get: reviews public actionresult index() { var model = 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 bother creating viewmodel, copying , pasting properties other classes it, , instantiating viewmodel? seems kind of redundant vs. joining tables, or there advantage missing? , yes, know typed , creating viewmodel names object have add properites class anyway, difference make if add them class or controller? matter, there equivalent select *
in linq? then, wouldn't have add properties controller every time change model.
take @ problem in passing anonymous type in view:
1.create controller pass anonymous types.
public actionresult index() { return view(new { testproperties="this test properties."}); }
2. check if data sent in view.
@model
3. let's access properties of anonymous type sent in our view.
@model.testproperties
accessing properties of anonymous type encounter error:
now let's create poco class viewmodel.
now value of viewmodel can access , create textbox using razor syntax.
Comments
Post a Comment