1

我使用 ASP.NET Web Api 构建了一个小型服务。我的域类如下所示:

 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; }
}

我的存储库如下所示:

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

我的控制器看起来像这样:

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

当我使用提琴手提出请求时,JSON结果如下:

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

如您所见,Ingridents 数组为空。这是为什么?

4

2 回答 2

2

您可以尝试使用急切加载Include

扩展您的GetAll方法以允许急切加载:

//...
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;
}

然后像这样在你的控制器中使用它:

public IEnumerable<Drink> GetAllDrinks()
{
    return _unitOfWork.Drinks.GetAll(d => d.Ingredients);
}
于 2013-01-05T17:03:41.933 回答
0

您是否首先使用实体​​框架代码?

如果是这样,您必须将导航属性标记为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; }
}
于 2013-01-05T15:11:22.510 回答