1

I'm trying to create a generic GetAll method that works for each of my model classes in my ASP.NET MVC4 project.

Here's my code:

public static List<T> GetAll(params string[] includeProperties)
{
    using (MovieSiteDb db = new MovieSiteDb())
    {
        var entities = db.Set<T>();
        foreach (var includeProperty in includeProperties)
        {
            entities.Include(includeProperty);
        }
        return entities.ToList();
    }
}

Now I call it the following way (Movie inherits the GetAll method):

Movie.GetAll("Category");

However I get an error when I try to access the foreign key "Category" in the view model. Why isn't it being included?

4

3 回答 3

6

我不能说我自己使用过 EF,但通常 LINQ 在您调用方法时不会改变查询 - 而是返回一个新查询。因此,如果您将代码更改为:

DbQuery<T> entities = db.Set<T>();
foreach (var includeProperty in includeProperties)
{
    entities = entities.Include(includeProperty);
}

您可能会发现解决了问题。

(类型entities现在固定为,DbQuery<T>而不是使用var隐式类型为DbSet<T>,作为Include返回DbQuery<T>。)

于 2013-10-18T10:05:13.490 回答
2

这是我的通用存储库的一部分,其中包含AllIncluding可以使用 lambda 表达式调用的方法

private readonly IUnitOfWork _UnitOfWork;

protected MyContext Context { get { return Uow.Context; } }

protected IUnitOfWork Uow
{
    get { return _UnitOfWork; }
}

public RepositoryBase(IUnitOfWork unitOfWork)
{
    _UnitOfWork = unitOfWork;
}

public virtual IQueryable<T> All
{
    get
    {
        return Context.Set<T>();
    }
}

public virtual IQueryable<T> AllIncluding(params Expression<Func<T
                                          , object>>[] includeProperties)
{
    IQueryable<T> query = All;
    foreach (var includeProperty in includeProperties)
    {
        query = query.Include(includeProperty);
    }
    //string sql = query.ToString();
    return query;
}

这是我如何从控制器中调用它的示例:

   IRepository<Answer> repo = _Uow.AnswerRepository;
   IOrderedQueryable<Answer> answers = repo.AllIncluding(answer => answer.Questions)
                                        .OrderBy(answer => answer.SortOrder)
                                        .ThenBy(answer => answer.Text);

在这里进入工作单元和其他东西

于 2013-10-18T10:31:41.767 回答
0

对于您对 lambda 表达式的关注,我知道您可以在下面做什么

var prodcutmasters = this.db.ProdcutMasters.Include(p => p.CategoriesMaster);
return (prodcutmasters.ToList());
于 2013-10-18T10:11:36.703 回答