其实我正在与Linq和UOW(工作单元)合作,并且我正在用linq轻松访问bbdd。我知道,如果我要得到一个表格的第一行,我可以这样做:选择top1与Linq
int test4 = (from p
in uow.ProductR.context.product
where p.Id == 1715 select p.Id).FirstOrDefault();
这将在SQL Server中执行此:
SELECT TOP (1)
[Extent1].[Id] AS [Id]
FROM [dbo].[product] AS [Extent1]
WHERE 1715 = [Extent1].[Id]
我的问题是,我可以做与LINQ一样反对我的UOW的通用储存库?我的意思是,当我执行
int test2 = uow.ProductR.Get(p => p.Id == 1715).Select(p => p.Id).FirstOrDefault();
或者
var test3 = uow.ProductR.Get(p => p.Id == 1715).Select(p => new { p.Id });
在SQL Server中,我得到:
SELECT
[Extent1].[Id] AS [Id],
[Extent1].[Name] AS [Name],
FROM [dbo].[product] AS [Extent1]
WHERE 1715 = [Extent1].[Id]
当然,用第二种方式,当数据库有50万行,它会很慢。 (我有更多的列,不仅2)
编辑:这里是用GET声明
public class GenericRepository<TEntity> : IGenericRepository<TEntity> where TEntity : class
{
internal contextEntities context;
internal DbSet<TEntity> dbSet;
public GenericRepository(contextEntities context)
{
this.context = context;
this.dbSet = context.Set<TEntity>();
}
public virtual IEnumerable<TEntity> Get(
Expression<Func<TEntity, bool>> filter = null,
Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> orderBy = null,
string includeProperties = "")
{
IQueryable<TEntity> query = this.dbSet;
if (filter != null)
{
query = query.Where(filter);
}
foreach (var includeProperty in includeProperties.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
{
query = query.Include(includeProperty);
}
if (orderBy != null)
{
return orderBy(query).AsQueryable();
}
else
{
return query.AsQueryable();
}
}
}
我希望我已经很好地解释了类。
“Get”方法是如何实现的?这个声明'uow.ProductR.Get(p => p.Id == 1715).Select(p => p.Id).FirstOrDefault();'应该使用'SELECT TOP 1' – Habib