Select set of values inside a LINQ query

0

Friends,

I'm trying to create the following .json with a LINQ query using Entity Framework 6:

   {
    "id": "1231-12321-sdff-21-31",
    "name": "nome do produto",
    "description": "Descrição do produto"
    "rating": 4.1,
    "price": 7.50,
    "photos": 
    [
     "http://path/photo.img",
     "http://path/photo.img"
    ]
}

My problem is in the selection of the sub-vector photos . When creating my query, Json returns me 2 identical objects, but each one with a photo. See:

[
    {
        "$id": "1",
        "id": "8514ba6c-1cbf-11e8-a84a-001dd8b7460e",
        "name": "Pão com frios",
        "description": "Pão recheado com frios",
        "rating": 5,
        "price": 2.50,
        "photos": {
            "$id": "2",
            "path": "foto/com/caminho"
        }
    },
    {
        "$id": "3",
        "id": "8514ba6c-1cbf-11e8-a84a-001dd8b7460e",
        "name": "Pão com frios",
        "description": "Pão recheado com frios",
        "rating": 5,
        "price": 2.50,
        "photos": {
            "$id": "4",
            "path": "caminho/da/imagem.png"
        }
    }
]

I know that my select is wrong .. I just have no idea how to make this query stay dynamic, depending on how many images I have to display. Here is my code:

List<ProductViewModel> products = await
    (from prod in db.product
    join prodPhoto in db.product_photo on prod.id equals prodPhoto.product_id
    where prod.id == id
    select new ProductViewModel
    {
        id = prod.id,
        name = prod.name,
        description = prod.description,
        rating = prod.rating,
        price = prod.price,
        photos = new HashSet<ProductPhotoViewModel>()
        {
            new ProductPhotoViewModel
            {
                path = prodPhoto.path
            }
        }
    }).ToListAsync();

My ProductViewModel object:

    public class ProductViewModel
    {
    public ProductViewModel()
    {
        photos = new HashSet<ProductPhotoViewModel>();
    }

    //Product
    public string id { get; set; }
    public string name { get; set; }
    public string description { get; set; }
    public int? rating { get; set; }
    public decimal price { get; set; }

    //Product photo
    public virtual ICollection<ProductPhotoViewModel> photos { get; set; }
}

and my ProductImageViewModel object:

    public class ProductPhotoViewModel
    {
        public string path { get; set; }
    }

I searched trying to use LINQ and lambda expressions, but I did not get anywhere.

How do you keep up with this problem?

    
asked by anonymous 29.03.2018 / 15:58

0 answers