Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement pivot data in Entity Framework?

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. enter image description here

But I want to convert it into Pivot view, something like this.

enter image description here

How can I do this by using Entity Framework or LINQ ? Thanks

like image 713
Shoaib Ijaz Avatar asked Sep 20 '25 22:09

Shoaib Ijaz


1 Answers

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

like image 141
Sir Rufo Avatar answered Sep 22 '25 13:09

Sir Rufo