I have created following models in ASP.NET MVC. Now I have to send products data by API or JSON format.
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public virtual IList<ProductAttribute> ProductAttributes { get; set; }
}
public class ProductAttribute
{
public int Id { get; set; }
public int ProductId { get; set; } //foreign key
public string Key { get; set; }
public string Value { get; set; }
}
Currently data comes in this way after converting into JSON.
But I want to convert it into Pivot view, something like this.
How can I do this by using Entity Framework or LINQ ? Thanks
I would change the output to
[
{
"Id": 21098,
"Name": "12 Port Fast USB Charging Station for iPad, iPhone",
"Attributes":{
"Size": "Large",
"Length": "Short"
}
}
]
The response class will look like
public class ProductResponse
{
public int Id { get; set; }
public string Name { get; set; }
public Dictionary<string,string> Attributes { get; set; }
}
and you can create the collection from your query
IList<ProductResponse> response = myContext.Set<Product>()
.Include( e => e.ProductAttributes )
.Where( e => e.Id == 21098 )
.Select( e => new ProductResponse {
Id = e.Id,
Name = e.Name,
Attributes = e.ProductAttributes.ToDictionary( e => e.Key, e => e.Value ),
} )
.ToList();
and return that collection
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With