locked
selecting all the fields from ProductVM instead of Selected field defined in query. RRS feed

  • Question

  • User271867911 posted

    I am trying to select the product image and <g class="gr_ gr_74 gr-alert gr_spell gr_inline_cards gr_run_anim ContextualSpelling ins-del multiReplace" id="74" data-gr-id="74">CataegoryName</g>. But Despite defining in the query . I am getting all the methods in fields from <g class="gr_ gr_215 gr-alert gr_spell gr_inline_cards gr_run_anim ContextualSpelling ins-del multiReplace" id="215" data-gr-id="215">ProductVM</g>

     IEnumerable<ProductVM> model = db.Products.OrderBy(x => x.ProductName).Select(r => new ProductVM
                    {
                        ProductName = r.ProductName,
                        CategoryName = r.Category.CategoryName
                   
                    }).ToList();
                    return model;

    Here the <g class="gr_ gr_290 gr-alert gr_spell gr_inline_cards gr_run_anim ContextualSpelling only-del replaceWithoutSep" id="290" data-gr-id="290">the results</g> the <g class="gr_ gr_238 gr-alert gr_spell gr_inline_cards gr_run_anim ContextualSpelling ins-del multiReplace" id="238" data-gr-id="238">reuslt</g> should contain only CategoryName and ProductName but it is showing all fields in product VM

    [{"ProductId":0,"ProductName":"Piazza","ProductImage":null,"Description":null,"DiscountedPrice":0.0,"CategoryName":"Junk","CategoryId":null,
    "IsErased":false,"ProductRegularPrice":0.0,"ModifiedTime":"0001-01-01T00:00:00"}]
    Sunday, November 26, 2017 8:42 PM

Answers

  • User991499041 posted

    Hi Farooqspecials,

    The query always returns ProductVM collection because of 

    r => new ProductVM

    You can specify the query return a list of a specific type. 

    Create a new class ProductModel

    public class ProductModel
    {
       public string ProductName { get; set; }
       public string CategoryName { get; set; }
    }

    and modify the query

    var model = db.Products.OrderBy(x => x.ProductName).Select(r => new ProductModel
    {
         ProductName = r.ProductName,
         CategoryName = r.Category.CategoryName
                   
    }).ToList();
    
    return model; 

    Finally you would get ProductModel collection which contain only CategoryName and ProductName property.

    Regards,

    zxj

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, November 27, 2017 2:22 AM