其實我正在與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