Ols1
Ols1

Reputation: 321

Web Api + Entity Framework Not properly loading data

I've built a small service using the ASP.NET Web Api. My domain classes looks like this:

 public class Drink : IEntity
{
    public Drink()
    {
        Ingridients = new List<Ingredient>();
    }

    public int Id { get; set; }
    public string Name { get; set; }
    public ICollection<Ingredient> Ingridients { get; set; }
    public string Approach { get; set; }
}

public class Ingredient : IEntity
{
    public Ingredient()
    {
        Drinks = new List<Drink>();
    }

    public int Id { get; set; }
    public string Name { get; set; }
    public ICollection<Drink> Drinks { get; set; }
}

My Repository Looks like this:

public IEnumerable<T> GetAll(){return _dbSet;}

And my controller looks like this:

    public IEnumerable<Drink> GetAllDrinks()
    {
        return _unitOfWork.Drinks.GetAll();
    }

When I make I request using fiddler the JSON result is the following:

{"Id":15,"Name":"Russian Energy","Ingridients":[],"Approach":"Mix Vodka with Redbull"}

As you can see the Ingridents array is empty. Why is that?

Upvotes: 1

Views: 1347

Answers (2)

Slauma
Slauma

Reputation: 177153

You can try to use eager loading with Include:

Extend your GetAll method to allow eager loading:

//...
using System.Data.Entity;
//...

public IEnumerable<T> GetAll(params Expression<Func<T, object>>[] includes)
{
    IQueryable<T> query = _dbSet;
    if (includes != null)
    {
        foreach (var include in includes)
            query = query.Include(include);
    }
    return query;
}

Then use it in your controller like so:

public IEnumerable<Drink> GetAllDrinks()
{
    return _unitOfWork.Drinks.GetAll(d => d.Ingredients);
}

Upvotes: 2

deerchao
deerchao

Reputation: 10544

Are you using Entity Framework Code First?

If so, you have to mark the navigation properties as virtual:

public class Drink : IEntity
{
    public Drink()
    {
        Ingridients = new List<Ingredient>();
    }

    public int Id { get; set; }
    public string Name { get; set; }
    public virtual ICollection<Ingredient> Ingridients { get; set; }
    public string Approach { get; set; }
}

public class Ingredient : IEntity
{
    public Ingredient()
    {
        Drinks = new List<Drink>();
    }

    public int Id { get; set; }
    public string Name { get; set; }
    public virtual ICollection<Drink> Drinks { get; set; }
}

Upvotes: 0

Related Questions