Skip to content

Support DateTime.ToString(string) #10227

Closed as duplicate
Closed as duplicate

Description

@los93sol

I have a query like db.Records.Where(record => (record.Created.ToString("MM/dd/yyyy hh:mm:ss tt") ?? "").ToLower().Contains("11/")).ToList(); where Created is a DateTime

The query that is generated does not contain any where so in this example it doesn't appear to have an effect, but when I add other criteria that limits the result set then we start to see the issue with the query not executing in SQL.

My use case here is that I have a table rendered on the page and I am setting the display format of the DateTime. I allow the user to search that table column, but to provide them reliable results I need to know the format the user sees to know how to search it in the database. The result set is huge so rendering everything in the client and sorting client side is not an option.

Further technical details

EF Core version: 2.0.0
Database Provider: Microsoft.EntityFrameworkCore.SqlServer
Operating system: Windows 10
IDE: Visual Studio 2017

Activity

  1. smitpatel commented on Nov 6, 2017

    @smitpatel
    Contributor

    Related #7364

  2. pmiddleton commented on Nov 7, 2017

    @pmiddleton
    Contributor

    @los93sol - It appears you want to allow your users to search the Created date for records created on specific days of the month, or months of the year?

    If that is the case then you can do the following

    int searchValue = 11 ;
    b.Records.Where(record => (record.Created.Month == searchValue || record.Created.Day == searchValue)).ToList();

    This will translate into DATEPART method calls.

  3. los93sol commented on Nov 7, 2017

    @los93sol
    Author

    Thanks for the suggestion, that is similar to what I’m trying to do, but I️ was hoping to allow the user to search it as a string to avoid building a picker for the UI

  4. smitpatel commented on Nov 7, 2017

    @smitpatel
    Contributor

    You could create a User defined function in your context for which you can provide a SQL translation and we would just invoke it on server. That would allow you to translate date to specific conversion format on server rest would just work.

    Example (Put this in your derived DbContext class

            protected override void OnModelCreating(ModelBuilder modelBuilder)
            {
                // Configure model
                modelBuilder.HasDbFunction(typeof(MyContext).GetMethod(nameof(MyContext.ToCustomString))).HasTranslation(
                    e =>
                    {
                        return new SqlFunctionExpression("convert",
                            typeof(string),
                            new[]{
                                new SqlFragmentExpression("VARCHAR(100)"),
                                e.First(),
                                new SqlFragmentExpression("101"), // Pick a style available on T-SQL. 
                            });
                    });
            }
    
            public static string ToCustomString(DateTime date)
            {
                return date.ToString("MM/dd/yyyy hh:mm:ss tt"); // You can just throw NotImplementedException too
            }

    Query

    var query = db.Blogs.Where(b => MyContext.ToCustomString(b.Created).ToLower().Contains("11/")).ToList();

    Generates SQL

          SELECT [b].[Id], [b].[Created]
          FROM [Blogs] AS [b]
          WHERE CHARINDEX(N'11/', LOWER(convert(VARCHAR(100), [b].[Created], 101))) > 0
  5. los93sol commented on Nov 7, 2017

    @los93sol
    Author

    Thank you! That's almost perfect and exactly what I was looking for, but I am in an abstraction layer where I am providing the functionality via an extension method of IQueryable and cannot figure out how to get at the modelBuilder. If I could sort that out then I think I know what to do from there to sort it on my end.

  6. smitpatel commented on Nov 7, 2017

    @smitpatel
    Contributor

    One restriction is method has to be static. You can move it to different type than DbContext if needed. To be able to call from IQueryable and OnModelCreating both you need to put in some place which is referenced by both.

  7. pmiddleton commented on Nov 7, 2017

    @pmiddleton
    Contributor

    One thing to consider is that you are going to have bad performance on with this query.

    The query is going to force a conversion on your Created column, from datetime to nvarchar, which will prevent using any indexes in the query.

    Depending on how big the table is this could be a problematic query.

  8. los93sol commented on Nov 7, 2017

    @los93sol
    Author

    @pmiddleton, thanks for pointing that out, my plan was to actually change this to use format instead of convert, thinking that would be more efficient in sql

  9. ajcvickers commented on Nov 8, 2017

    @ajcvickers
    Contributor

    Duplicate of #7364

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions