我正在尝试创建一个通用的GetAll方法,该方法适用于我的ASP.NET MVC4项目中的每个模型类。
这是我的代码:
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();
}
}
现在我按以下方式调用它(Movie继承了GetAll方法):
Movie.GetAll("Category");
但是当我尝试访问视图模型中的外键“类别”时出现错误。 为什么不包含它?
答案 0 :(得分: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>
}}。)
答案 1 :(得分: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;
}
以下是我如何通过Controller调用它的示例:
IRepository<Answer> repo = _Uow.AnswerRepository;
IOrderedQueryable<Answer> answers = repo.AllIncluding(answer => answer.Questions)
.OrderBy(answer => answer.SortOrder)
.ThenBy(answer => answer.Text);
在这里进入工作单位和其他东西'
答案 2 :(得分:0)
关于lambda表达的关注,我知道你可以在下面做什么
var prodcutmasters = this.db.ProdcutMasters.Include(p => p.CategoriesMaster);
return (prodcutmasters.ToList());