【发布时间】:2021-07-09 16:39:56
【问题描述】:
我正在创建一个内部 Razor Pages 应用程序,该应用程序使用实体框架连接到 SQL 数据库。我有一个带有搜索表单的页面,我希望能够根据输入的日期搜索记录。
这是我目前所拥有的:
public async Task OnGetAsync(string searchString)
{
// provide an IQueryable list of web registrants that can be parsed.
// IQueryable<Models.WebPestMSTR> webRegistrationIQ = (from a in _context.WebPestMSTR
// select a);
// If the Search string is empty than only show the unprocessed web registration. Otherwise parse the table for matching records.
if (!String.IsNullOrEmpty(searchString))
{
// There is a search parameter. Parse the query for matching records.
// Parse the search parameter to see if it is a date (bool isCertNo = BigInteger.TryParse(searchString, out numOut);)
if (DateTime.TryParse(searchString, out DateTime dateTime))
{
WebPestMSTR = await _context.WebPestMSTR
.Where(a => a.DateAdded.ToShortDateString() == dateTime.ToShortDateString())
.Include(w => w.Course)
.Include(w => w.MiraInfo)
.ToListAsync();
// webRegistrationIQ = webRegistrationIQ.Where(a => a.DateAdded.ToShortDateString() == dateTime.ToShortDateString());
}
else
{
IQueryable<Models.WebPestMSTR> webRegistrationIQ = (from a in _context.WebPestMSTR
select a);
webRegistrationIQ = webRegistrationIQ.Where(a => a.LastName.Contains(searchString));
WebPestMSTR = await webRegistrationIQ
.Include(w => w.Course)
.Include(w => w.MiraInfo)
.ToListAsync();
}
}
else
{
// No search parameters so only show unprocessed records.
WebPestMSTR = await _context.WebPestMSTR
.Include(w => w.Course)
.Include(w => w.MiraInfo)
.Where(w => w.IsProcessed == false)
.ToListAsync();
}
}
如果是日期,我能够成功解析 searchString,但在哪里出错。错误是:
InvalidOperationException:LINQ 表达式 'DbSet .Where(w => w.DateAdded.ToShortDateString() == __ToShortDateString_0)' 无法翻译。以可翻译的形式重写查询,或通过插入对 AsEnumerable()、AsAsyncEnumerable()、ToList() 或 ToListAsync() 的调用显式切换到客户端评估。
按姓氏搜索时搜索正常。
有什么想法吗?
【问题讨论】:
-
您使用的是什么数据库(Sql server 或其他)?
-
Visual Studio 社区自带的 SQL Server (localDb)。
-
该项目也在使用 AspNetCore v3.1.9 和 Entity Framework Core 3.1.13。
标签: c# asp.net-core .net-core entity-framework-core razor-pages