I'm converting an old SQL Server DB design to EF Core 2.21. The DB design is not practical to change. One field is a Char(1) with 'X' for true. I've added a .HasConversion however it is not working. The values are not converted and after a change and trying to save I get "Object of type 'System.Boolean' cannot be converted to type 'System.String". I am referencing https://docs.microsoft.com/en-us/ef/core/modeling/value-conversions where it says conversions can be from a value of one type to a value of another type. What am I missing? Can this be done?
entity.Property(e => e.LockNote)
.HasColumnName("LOCK_NOTE")
.HasMaxLength(1)
.IsUnicode(false)
.HasConversion(v => v == "X" ? true : false, v => v == true ? "X" : "");
You could try to use built-in BoolToStringConverter:
var converter = new BoolToStringConverter("", "X");
entity.Property(e => e.LockNote)
.HasColumnName("LOCK_NOTE")
.HasMaxLength(1)
.IsUnicode(false)
.HasConversion(converter);
Thanks to both Ivan an Yuri. You both lead me to the answer that was not at all intuitive for me. The LockNote field is a Char(1) field that had come over as a string property in the table class. I needed to change that in the table class to a bool property and then I used the following:
var boolCharConverter =
new ValueConverter<bool, string>(v => v ? "X" : "", v => v == "X");
entity.Property(e => e.LockNote)
.HasColumnName("LOCK_NOTE")
.IsUnicode(false)
.HasConversion(typeof(string))
.HasConversion(boolCharConverter);
with further testing it turns out that I can also remove the following without issues and further simplify the solution.
.IsUnicode(false)
.HasConversion(typeof(string))