Entity Framework + Fluent API + Web API?

1

I'm having trouble mapping the category within a product, when I'm ready the products the category ( virtual class ) comes empty, even with CategoryId filled.

Product

public class Product
{
    public Product()
    {
        this.LastUpdate = DateTime.Now;
    }

    public int Id { get; set; }
    public string Title { get; set; }
    public decimal Price { get; set; }
    public DateTime LastUpdate { get; set; }
    public int CategoryId { get; set; }
    public virtual Category Category { get; set; }

    public override string ToString()
    {
        return this.Title;
    }
}

Product Map

public class ProductMap : EntityTypeConfiguration<Product>
{

    public ProductMap()
    {
        ToTable("Product");
        HasKey(x => x.Id);
        Property(x => x.Title).HasMaxLength(160).IsRequired();
        Property(x => x.Price).IsRequired();
        Property(x => x.LastUpdate).IsRequired();

        HasRequired(x => x.Category);

    }
}

Category

public class Category
{
    public int Id { get; set; }
    public string Title { get; set; }

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

    public override string ToString()
    {
        return this.Title;
    }
}

Category Map

public class CategoryMap : EntityTypeConfiguration<Category>
{
    public CategoryMap()
    {
        ToTable("Category");
        HasKey(x => x.Id);
        Property(x => x.Title).HasMaxLength(60).IsRequired();

        HasMany<Product>(x => x.Products).WithRequired(c => c.Category);
    }
}

GetProducts

// GET: api/Product
public IQueryable<Product> GetProducts()
{
    db.Configuration.ProxyCreationEnabled = false;
    return db.Products;
}

Return

{
    "Id": 1,
    "Title": "Produto Eletrônico",
    "Price": 10010,
    "LastUpdate": "2015-10-29T18:28:19.547",
    "CategoryId": 1,
    "Category": null
}
    
asked by anonymous 29.10.2015 / 21:33

1 answer

1

Try changing your method with:

public IQueryable<Product> GetProducts()
{
    db.Configuration.ProxyCreationEnabled = false;
    var query = from r in db.Products.Include("Category") select r;
    return query;
}
    
06.06.2017 / 13:44