Skip to content

Allow HasConversion/ValueConverters to convert nulls #13850

Description

@MarkGodwin

There are significant problems when executing queries that either convert nulls in the database to non-nulls in code or vice-versa. Therefore, we have marked this feature as internal for EF Core 6.0. You can still use it, but you will get a compiler warning. The warning can be disabled with a #pragma. See #26230 for more information.


When using FromSql to create a custom filtered data set, any column conversions defined on the DbQuery object don't get applied.

I think the column conversions should be included automatically around the sub-query supplied to FromSql, similar to how a sub-query is used if more predicates are added to the IQueryable.

    public class Model
    {
        public int Id { get; set; }
        public bool Flag { get; set; }
    }

    public partial class MyDbContext : DbContext
    {
        public DbQuery<Model> Models { get; set; }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
                    modelBuilder.Query<Models>(
                        entity =>
                        {
                            entity.ToView("dbo.Models");
                            // Convert null Flag to false on way in
                            entity.Property(e => e.Flag).HasConversion<bool?>(f => f, t => t ?? false);
                        });
        }
    }

    // ...

    var models = dbContext.Models.FromSql("SELECT * FROM dbo.Models").ToList();

This, I think, should result in SQL similar to this being executed...

SELECT [e].[Id], COALESCE([e].[Flag], 0) AS [Flag]
FROM (
    SELECT * FROM dbo.Models) AS [e];

But, in reality, the plain SQL from FromSql is executed

SELECT * FROM dbo.Models

EF Core version: 2.1.4
Database Provider: Microsoft.EntityFrameworkCore.SqlServer
Operating system: Windows 7
IDE: Visual Studio 2017 15.8.5

Activity

  1. ajcvickers commented on Nov 1, 2018

    @ajcvickers
    Contributor

    @MarkGodwin Value conversions are not translated to SQL--that feature is tracked by #10861. Instead, the value is read from the database and then converted. This is because the primary purpose of this feature it to allow use of types that cannot be directly read from or written to the database.

    Also, value converters do not generally allow the conversion of null to some other value. This is because the same value converter can be used for both nullable and non-nullable types, which is very useful for PK/FK combinations where the FK is often nullable and the PK is not. We will discuss whether or not to add support for converting nulls.

  2. MarkGodwin commented on Nov 1, 2018

    @MarkGodwin
    Author

    Sorry, I can see that I am guilty of making assumptions that I didn't verify before raising the issue. I misinterpreted the documentation about where value converters are executed, and then jumped to conclusions about why it wasn't working in my particular case.

    The inability to translate null is also very clearly described in the documentation.

    I... assume... a correctly implemented value converter would be executed when mapping the results of a FromSql. So I'll close this off immediately.

    Apologies again.

  3. changed the title [-]HasConversion property configuration not applied to FromQuery results[/-] [+]Allow HasConversion/ValueConverters to convert nulls[/+] on Nov 5, 2018
  4. added this to the Backlog milestone on Nov 5, 2018
  5. space-alien commented on Mar 12, 2019

    @space-alien

    The inability to translate nulls leads to some pretty unintuitive behaviour:

    modelBuilder.Entity<Person>()
        .Property(p => p.Address).HasConversion(
            address => JsonConvert.SerializeObject(address),     // Address is a value object
            str => JsonConvert.DeserializeObject<Address>(str));

    The above is mapped to a nullable string column in the DB. If Address is null, a NULL is inserted into the row and vice versa. So far so good.

    But the results of following query include entities where Address is null!

    _context.People.Where(c => c.Address != null).ToList()
  6. Skulblaka commented on Apr 8, 2019

    @Skulblaka

    I ran into a problem when I tried to add a ValueConverter<float, float?> that converts float.NaN to null and vice versa since SQL Server's real data type does not support NaN. The generated columns for the properties with the converter did not allow null values; I guess this is related?

  7. ajcvickers commented on Apr 8, 2019

    @ajcvickers
    Contributor
  8. UdiAzulay commented on Oct 13, 2019

    @UdiAzulay

    any success to use conversion from non null to nullable type? (without excluding the property using NonMapped)

  9. UdiAzulay commented on Oct 13, 2019

    @UdiAzulay

    found an ugly solution using ValueConverter<T, T?>(optionally) and the below reflection field update

    prop.Metadata.GetType().GetField("_isNullable", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic).SetValue(prop.Metadata, true);

  10. 52 remaining items

  11. removed their assignment
    on Aug 31, 2024
  12. ajcvickers commented on Nov 19, 2024

    @ajcvickers
    Contributor

    Notes from team meeting: I was thinking about this again following investigation of #35051 and I think the cases where nulls have special behavior--for example, when used in a PK or FK column/property--can be detected in model validation. This will allow us to mark this code as public to support the cases that work well, while still generating a warning (possibly as an error by default) for cases where the behavior may be unexpected.

  13. self-assigned this
    on Nov 19, 2024
  14. modified the milestones: Backlog, 10.0.0 on Nov 19, 2024
  15. AndriySvyryd commented on Nov 19, 2024

    @AndriySvyryd
    Member

    Also, for columns of optional dependents using table sharing.

  16. ivebeenlinuxed commented on May 29, 2025

    @ivebeenlinuxed

    I had some success with adding ConvertsNulls... I'm writing this a little confused, because if it it really was that simple, surely someone else would be doing it and this topic wouldn't be here....

    using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
    
    public class NeverNullStringColumn : ValueConverter<string?, string>
    {
        
        public override bool ConvertsNulls => true;
        public NeverNullStringColumn()
            : base(
                v => v ?? string.Empty,
                v => v == string.Empty ? null : v)
        {
        }
    }
    
  17. modified the milestones: 10.0.0, Backlog on Jun 20, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Projects

No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions