获取匹配行的 Id - 两种方法之间有什么性能差异?
fetching Id for matching row - any performance difference between two approaches?
我有returnsGuid?
的方法。我遇到了两种获取 matching Id from table
的方法。
1- Which one is the preferred way or its just personnel preference?
2- Any performance difference?
private Guid? findCustomerId(string customerNo)
{
// 1st way
return _context.Customers.FirstOrDefault(x => x.Code == customerNo).Id;
// 2nd way
return _context.Customers.Where(x => x.Code == customerNo).Select(y => y.Id).FirstOrDefault();
}
两种方法生成相同的 sql,但有一个区别 - 所选行的 return 列:
// 1st way - Returns entire record to memory and then you decide to take just ID
return _context.Customers.FirstOrDefault(x => x.Code == customerNo).Id;
// 2nd way - Returns just the column of ID to memory
return _context.Customers.Where(x => x.Code == customerNo).Select(y => y.Id).FirstOrDefault();
如果您从生成的 sql 中删除列,您可以看到它们在做同样的事情。
//Approach 1:
SELECT [Limit1].[Id] AS [Id]
FROM ( SELECT TOP (1) *
FROM [dbo].[Customers] AS [Extent1]
WHERE ([Extent1].[Code] = @p__linq__0)
OR (([Extent1].[Code] IS NULL) AND (@p__linq__0 IS NULL))
) AS [Limit1]
//Approach 2:
SELECT TOP (1) *
FROM [dbo].[Customers] AS [Extent1]
WHERE ([Extent1].[Code] = @p__linq__0)
OR (([Extent1].[Code] IS NULL) AND (@p__linq__0 IS NULL))
- 两个查询都检索
TOP (1)
条记录
WHERE
子句相同
- 第一种方法中的嵌套
SELECT
对性能没有影响
如果您没有因检索整个记录而导致的任何严重性能问题(或者如果您的列包含大量数据字段),那么请考虑可读性 - 我认为第一种方法更具可读性
我有returnsGuid?
的方法。我遇到了两种获取 matching Id from table
的方法。
1- Which one is the preferred way or its just personnel preference?
2- Any performance difference?
private Guid? findCustomerId(string customerNo)
{
// 1st way
return _context.Customers.FirstOrDefault(x => x.Code == customerNo).Id;
// 2nd way
return _context.Customers.Where(x => x.Code == customerNo).Select(y => y.Id).FirstOrDefault();
}
两种方法生成相同的 sql,但有一个区别 - 所选行的 return 列:
// 1st way - Returns entire record to memory and then you decide to take just ID
return _context.Customers.FirstOrDefault(x => x.Code == customerNo).Id;
// 2nd way - Returns just the column of ID to memory
return _context.Customers.Where(x => x.Code == customerNo).Select(y => y.Id).FirstOrDefault();
如果您从生成的 sql 中删除列,您可以看到它们在做同样的事情。
//Approach 1:
SELECT [Limit1].[Id] AS [Id]
FROM ( SELECT TOP (1) *
FROM [dbo].[Customers] AS [Extent1]
WHERE ([Extent1].[Code] = @p__linq__0)
OR (([Extent1].[Code] IS NULL) AND (@p__linq__0 IS NULL))
) AS [Limit1]
//Approach 2:
SELECT TOP (1) *
FROM [dbo].[Customers] AS [Extent1]
WHERE ([Extent1].[Code] = @p__linq__0)
OR (([Extent1].[Code] IS NULL) AND (@p__linq__0 IS NULL))
- 两个查询都检索
TOP (1)
条记录 WHERE
子句相同- 第一种方法中的嵌套
SELECT
对性能没有影响
如果您没有因检索整个记录而导致的任何严重性能问题(或者如果您的列包含大量数据字段),那么请考虑可读性 - 我认为第一种方法更具可读性