[英].NET Core 3.1 Linq and SQL Server can not translate DateTime
I have a project that is running on .NET Core 3.1 and has Entity Framework Core included.我有一个项目正在 .NET Core 3.1 上运行,并且包含 Entity Framework Core。
My problem is I am trying to filter an object by a datetime
field.我的问题是我试图通过datetime
时间字段过滤 object。 The search term is a string and can be anything.搜索词是一个字符串,可以是任何东西。 The DateTime
field is being displayed in the format yyyy-MM-dd
so I believe that using that format in the ToString
is appropriate. DateTime
字段以yyyy-MM-dd
格式显示,因此我认为在ToString
中使用该格式是合适的。
Here is the code:这是代码:
entitiesFromRepository = entitiesFromRepository.Where(m => m.DepartureDate.ToString("yyyy-MM-dd").Contains(searchTerm));
The entitiesFromRepository
is an IQueryable
. entitiesFromRepository
是一个IQueryable
。
The issue I believe is the ToString
with a date format, as when I take the date format out it works.我认为问题是带有日期格式的ToString
,因为当我取出日期格式时它可以工作。
Can anyone help here?有人可以帮忙吗?
You can try TryParse your "search term"你可以试试 TryParse 你的“搜索词”
DateTime date;
DateTime.TryParse("search term", out date);
entitiesFromRepository = entitiesFromRepository.Where(m => m.DepartureDate.Date == date).ToList();
//this will work perfect if your "search term" comes as "2022-03-31" eg
It's not supported to use .ToString()
on datetime but there is a trick that you can achieve your query like this:不支持在 datetime 上使用.ToString()
但有一个技巧可以让您像这样实现查询:
entitiesFromRepository.Where(x =>
(x.DepartureDate.Year.ToString()
+ "-" +
x.DepartureDate.Month.ToString()
+ "-" +
x.DepartureDate.Day.ToString())
.Contains(searchTerm));
I've tested in .net 6 and works fine but I think it should work on .netcore 3.1 too.我在 .net 6 中测试过并且工作正常,但我认为它也应该在 .netcore 3.1 上工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.