开发者

ASP.NET MVC MODEL - Passing Joins created on Models to Controllers and Views with scaffold

this is the case: ASP.NET MVC C#

Model: I would like to use information defined on three tables, Product - Details - Pictures. I created a ProductRepository and defined a join of the three tables. Finally I select fields from each of these tables.

    public IQueryable ProductsList()
    {
        var db = new Entities();
        var results = from p in db.Products
                    join pi in db.ProductPic on p.Produc开发者_运维技巧tId equals pi.ProductId
                    // first join
                    join pv in db.ProductDetails on p.ProductId equals pv.ProductId
                    // second join
                    select new
                               {
                                   p.Name,
                                   p.Description,
                                   p.PCategory,
                                   p.ProductPicture,
                                   pv.Price,
                                   pi.Picture,
                               };
        return (results);
    }

Controller: I defined:

    public ActionResult Index()
    {
        var products = productrepository.ProductsList();
        if (products == null) throw new NotImplementedException();
        else
        return View("Index", products);
    }

Views: I created a strongly typed view from model Products.

When I create the view I only received the fields from Table Product, but not the fields from table Details and Picture.

My main question resides in the way it has to be created a View in order to use all the fields defined on the model (in this case = productrepository.productslist(); At this moment when I scaffold directly I only receive fields from product using strongly typed with product.

Thank you so much!.


You strongly-typed your view to a Product type but your EF query returns an anonymous type that includes other fields. Create a class for the product view model:

class ProductViewModel
{
    public string Name { get; set; }
    public string Description{ get; set; }
    public string PCategory{ get; set; }
    public string ProductPicture{ get; set; }
    public string Price { get; set; }
    public string Picture { get; set; }
}

Then in the select of your EF query, populate this type rather than your anonymous type. Also, you should independently verify that your EF query is returning the expected results.


You may want to return a named type from ProductsList() instead of an anonymous one. You could then use that type name in your view.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜