c# - 使用 Linq 选择 top1

标签 c# sql-server asp.net-mvc linq unit-of-work

实际上,我正在使用 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 需要返回一个 IQueryable,而不是像现在这样返回一个 IEnumerable。然后,Get 的参数也变得毫无用处,因为调用者只需执行 Get().Where(...)。 API 表面变得更干净,因为您可以删除参数。

但是您正在失去对数据库查询方式的控制。我假设你正在做一个用于测试目的的存储库(如果不是,那么拥有一个可能是一个糟糕的选择)。测试以这种方式执行的查询变得更加困难。

关于c# - 使用 Linq 选择 top1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33964709/

相关文章:

c# - 在没有单元测试框架的情况下使用 Specflow

C#/.NET(核心): Is the type system safe enough to prevent SQL injections?

asp.net - 保护 ASP.NET MVC 应用程序中的 ajax 调用的安全

asp.net-mvc - 将ajax post的返回数据转移到隐藏? ASP.NET MVC

c# - ASP.NET MVC 中的递归

c# - 使用WebClient时如何绕过系统代理

php - 我可以忽略另一个 sql 查询中的 where 子句吗

c# - 从不同的表中检索数据

sql - 设置和更改 SQL Server 排序规则

c# - 请求被中止无法在共享主机服务器 C# 上创建 ssl/tls 安全通道