C# 为什么tolist只需花费1项的时间太长?
我对SQL Server进行存储过程调用,并尝试只获取1项。db立即返回,但是当我尝试使用C# 为什么tolist只需花费1项的时间太长?,c#,asp.net-core,C#,Asp.net Core,我对SQL Server进行存储过程调用,并尝试只获取1项。db立即返回,但是当我尝试使用ToList() 存储过程方法: public class EFRepository<T> : IRepository<T> where T : BaseEntity { private readonly ApplicationDbContext _context; private DbSet<T> _entities;
ToList()
存储过程方法:
public class EFRepository<T> : IRepository<T> where T : BaseEntity
{
private readonly ApplicationDbContext _context;
private DbSet<T> _entities;
public EFRepository(ApplicationDbContext context)
{
this._context = context;
}
public IQueryable<T> ExecuteStoredProcedureList(string commandText, params object[] parameters)
{
return _context.Set<T>().FromSql(commandText, parameters);
}
}
SQL Server中的存储过程会立即返回,因此这不是存储过程问题(直接测试以在数据库上运行)
从point var结果到下一个命令,您可以看到,对于仅包含几个数字字段的1个简单项ProductSimple
,它需要高达467ms的时间,我尝试来回移动调试点以检查速度,但它仍然保持相同的时间
在另一个项目中,这个ToList()
对于相同的项结构转换得非常快。我可能犯了什么错误
我正在使用ASP.NET Core 2.2.4和EF Core 2.2.4查询不会立即返回。在.ToList调用之前,查询实际上不会执行
查询返回所需的时间取决于连接到数据库的时间以及查询的效率。我们如何知道您是否发布linq代码:p也读取
。ToList()
将查询发送到dbMost可能,查询
是可查询的。这意味着实际的查询执行会被延迟,并在调用“.ToList”时运行。然而,由于您没有提供实际的查询,我们无法猜测为什么需要“这么长时间”。是的,但我们不知道查询表是什么样的,没有linq/lambda语法。这可能是由于客户端评估(默认设置下,用户应在日志中看到警告)或其他强制在本地对其进行评估的原因
public class EFRepository<T> : IRepository<T> where T : BaseEntity
{
private readonly ApplicationDbContext _context;
private DbSet<T> _entities;
public EFRepository(ApplicationDbContext context)
{
this._context = context;
}
public IQueryable<T> ExecuteStoredProcedureList(string commandText, params object[] parameters)
{
return _context.Set<T>().FromSql(commandText, parameters);
}
}
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
base.OnModelCreating(builder);
builder.Entity<Product>()
.ToTable("Product")
.Ignore(p => p.ProductFinalCost);
}
}
var query = _productRepository.ExecuteStoredProcedureList("dbo.[SearchProducts] " +
"@Keywords, @PageIndex,@PageSize,@SortBy,@FromDate, @ToDate,@Sku,@CreateBy,@CategoryIds,@OrderIds,@ShowPublished,@Discontinued,@Discount,@LoadFilterableSpecificationAttributeOptionIds, @FilterableSpecificationAttributeOptionIds OUTPUT,@PriceMin,@PriceMax,@ShowExpiredProduct,@FilterableBrands OUTPUT,@TotalRecords OUTPUT,@FilteredSpecs, @FilteredBrands,@LoadSimple,@TrungvangPick",
pKeywords,
pPageIndex,
pPageSize,
pSortBy,
pFromDate,
pToDate,
pSku,
pCreatedBy,
pCategoryIds,
pOrderIds,
pShowPublished,
pDiscontinued,
pDiscount,
pLoadFilterableSpecificationAttributeOptionIds,
pFilterableSpecificationAttributeOptionIds,
pPriceMin,
pPriceMax,
pShowExpiredProduct,
pFilterableBrands,
pTotalRecords,
pFilteredSpecs,
pFilteredBrands,
pLoadSimple,
pTrungvangPick
);
var result = query.ToList();
int totalRecords = pTotalRecords.Value != DBNull.Value ? Convert.ToInt32(pTotalRecords.Value) : 0;