0
votes

I have a web api which has a method to get products. The products belong to a category. Now to get to the problem, when i call the api, it returns a json object of the products but the products dont seem to have the category they belong in. I have also tried to use the OData expand on the browser but nothing different happens with regards to the json and the query that is sent to the DB.

The code below is my api method.

public IQueryable<Product> Get()
{
    var store = new DatabaseContext();

    return store.Products;
}

Product class

public class Product
{
    public int ProductId { get; set; }
    public string Name { get; set; }
    public int CatId { get; set; }

    public virtual Category Category { get; set; }
}

Category class

public class Category
{
    public int CategoryId { get; set; }
    public string Name { get; set; }

    public virtual ICollection<Product> Products { get; set; }

}

Database mapping

   public class ProductConfig : EntityTypeConfiguration<Product>
{
    public ProductConfig()
    {
        HasKey(m => m.ProductId)
            .Property(m => m.ProductId)
            .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);

        HasRequired(m => m.Category)
            .WithMany(m => m.Products)
            .HasForeignKey(m => m.CatId);
    }
}

public class CategoryConfig : EntityTypeConfiguration<Category>
{
    public CategoryConfig()
    {
        HasKey(m => m.CategoryId)
            .Property(m => m.CategoryId)
            .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
    }
}    

JSON Result on the browser

[
  {
    ProductId: 2,
    Name: "Malva Pudding",
    CatId: 1,
    Category: null
  },
  {
    ProductId: 3,
    Name: "Ultra mel",
    CatId: 1,
    Category: null
  }
]
2
You say you have tried using OData... Are you using the [Queryable] attibute on your controller action?beyond-code
Yes I am. If you can, may you kindly try to model a db based on the classes provided on the post.CodeNoob

2 Answers

0
votes

Are you using the right version of Web Api OData? I think this behavior you get when using the version 4... try updating your package at: Microsoft.AspNet.WebApi.OData

0
votes

It seams that OData model builder uses only Product class and annotations in it. There is lack of fluent mapping for OData