Skip to content

SqlServer: Translate bool ToString #14205

Closed
Closed

Description

@MaxG117

What's the idea behind converting values to string (using either object.ToString() or Convert.ToString(object))? Should the resulting string be compatible with the C# or the server-side string representation of the object?

For example, a C# bool is stored in a SqlServer bit column. Should conversion to string result in "0" and "1" or "true" and "false"?

Activity

  1. smitpatel commented on Dec 18, 2018

    @smitpatel
    Contributor

    "true" or "false". C# representation. It could be achieved via conditional for bool case or for other case where it is not possible it should not try to convert to string on server. Especially in scenarios where there are value converters applied.

  2. MaxG117 commented on Dec 18, 2018

    @MaxG117
    Author

    I don't follow. SqlServerObjectToStringTranslator translates boolValue.ToString() into "CONVERT(VARCHAR(5), boolValue)". I believe the result of this is "0" and "1", not "true" and "false". I do not see any "conditional for bool case".

  3. smitpatel commented on Dec 18, 2018

    @smitpatel
    Contributor

    Then it's a bug.

  4. MaxG117 commented on Dec 18, 2018

    @MaxG117
    Author

    You sound uncertain, and I too could be wrong (just because I don't see a "conditional for bool case" doesn't mean it's not there). Could you have someone look at the source code, confirm whether this is indeed a bug and explain what the fix should be? If it's a bug, then there's probably a missing test.

  5. smitpatel commented on Dec 18, 2018

    @smitpatel
    Contributor
                    var query = db.Blogs.Where(b => b.Value.ToString() == "true").ToList();
                    Console.WriteLine(query.Count);

    outputs following SQL

          SELECT [b].[Id], [b].[Value]
          FROM [Blogs] AS [b]
          WHERE CONVERT(VARCHAR(5), [b].[Value]) = N'true'

    Which of course produces incorrect results. EF Core 2.2.0

  6. changed the title [-]Question about query translation in SqlServerObjectToStringTranslator and SqlServerConvertTranslator[/-] [+]SqlServerObjectToStringTranslator converts bool value to server side incorrectly[/+] on Dec 18, 2018
  7. added this to the Backlog milestone on Dec 19, 2018
  8. MaxG117 commented on Dec 19, 2018

    @MaxG117
    Author

    What about other types, like DateTime? Should dateTime.ToString() and Convert.ToString(dateTime) also return the C# representation of those strings?

  9. smitpatel commented on Dec 19, 2018

    @smitpatel
    Contributor

    @MaxG117 - Isn't that covered in #14193 already?

  10. MaxG117 commented on Dec 19, 2018

    @MaxG117
    Author

    @smitpatel That's the issue where I pointed out an inconsistency between dateTime.ToString() and Convert.ToString(dateTime), but it does not describe the expected string format.

    Additionally, DateTimeOffset has a bigger problem, because there's no Convert.ToString(DateTimeOffset) method. You may want to split this up into three separate bugs. For now, I'm looking for guidance regarding expected string formats.

  11. smitpatel commented on Dec 19, 2018

    @smitpatel
    Contributor

    @MaxG117 - For expected string format you can read discussion here #7364

    Essentially, we are not going to do anything other than default unless there is really strong demand for it.

    #14193 - Will track to make all possible conversions (initiated through instance.ToString or Convert.ToString), work in default format. It is an enhancement.
    This issue is bug - at the very least, the bool values needs to be stopped from going to server translation.
    We are not going to look at all formatters. Any specific formatter would be high user feedback based.

    If you want your custom formatter to be used server side, then you can add DbFunction in EF Core which would map to server with your specified formatter and we will translate into it during query.

  12. MaxG117 commented on Dec 20, 2018

    @MaxG117
    Author

    @smitpatel

    For expected string format you can read discussion here #7364

    Actually I think #6264 is more relevant to my question.

    This issue is bug - at the very least, the bool values needs to be stopped from going to server translation

    I believe it is not ideal to stop bool values from going to server translation. For example, if a bool is used in a Where clause, the client would end up fetching and processing the entire result set. I realize nobody in their right mind should be converting booleans to strings in the Where clause (or anywhere, really), but as long as conversion of boolean to string is supported, it may as well be translated on the server.

  13. smitpatel commented on Dec 21, 2018

    @smitpatel
    Contributor

    I believe it is not ideal to stop bool values from going to server translation.

    Yes, it is not ideal. But doing client eval rather than giving incorrect result is much better. Incorrect results could cause data corruption.

  14. MaxG117 commented on Dec 21, 2018

    @MaxG117
    Author

    doing client eval rather than giving incorrect result is much better

    Why would translating a boolean to a string on the server produce incorrect results?

    By the way, your example above:

    var query = db.Blogs.Where(b => b.Value.ToString() == "true").ToList();

    wouldn't work, because true.ToString() returns "True" (capitalized).

    I'm suggesting doing everything on the server, so that this query:

          bool myBool = true;
          var query = db.Blogs.Where(b => b.Value.ToString() == myBool.ToString()).ToList();

    produces the following SQL:

          SELECT [b].[Id], [b].[Value]
          FROM [Blogs] AS [b]
          WHERE [b].[Value] = 1
  15. 13 remaining items

  16. MaxG117 commented on Apr 29, 2021

    @MaxG117
    Author

    By the way, a similar fix should also go into SqlServerConvertTranslator.cs. In my provider's implementation I added typeof(Boolean) to _supportedTypes and changed the Translate method to look something like the following. I also improved on the original by removing an unnecessary CONVERT that was being added for Convert.ToString(String).

    public SqlExpression Translate(SqlExpression instance, MethodInfo method, IReadOnlyList<SqlExpression> arguments)
    {
        if (_supportedMethods.Contains(method))
        {
            if (method.Name == nameof(Convert.ToString))
            {
                if (arguments[0]?.Type == typeof(string))
                {
                    // avoid unnecessarily conversion of string to string
                    return arguments[0];
                }
                else if (arguments[0]?.Type == typeof(bool))
                {
                    // Convert a bool to its string representation
                    return _sqlExpressionFactory.Case(
                        new[] 
                        { 
                            new CaseWhenClause(
                                _sqlExpressionFactory.Equal(arguments[0], _sqlExpressionFactory.Constant(false)),
                                _sqlExpressionFactory.Constant(false.ToString())) 
                        },
                        _sqlExpressionFactory.Constant(true.ToString()));
                }
            }
    
            // original return here:
            return _sqlExpressionFactory.Function(
                "CONVERT",
                new[] { _sqlExpressionFactory.Fragment(_typeMapping[method.Name]), arguments[0] },
                method.ReturnType);
        }
        else
        {
            return null;
        }
    }
  17. added and removed
    good first issue
    on May 6, 2021
  18. modified the milestones: Backlog, 6.0.0 on May 6, 2021
  19. modified the milestones: 6.0.0, on May 27, 2021
  20. modified the milestones: , 6.0.0 on Nov 8, 2021
  21. added theissue type on Jun 15, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions