【发布时间】:2015-11-27 20:59:38
【问题描述】:
实际上,我正在使用 Linq 和 UOW(工作单元),并且我正在使用 linq 轻松访问 bbdd。我知道如果我想获取一个表的第一行,我可以这样做:
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]
当然,使用第二种方式,当数据库有 500k 行时,它会很慢。 (我的专栏更多,不止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
标签: c# sql-server asp.net-mvc linq unit-of-work