I am trying to use a valueconverter to convert a timespan to a string.
My code thus far is:
entity.Property(e => e.DropOffTime).HasConversion(
v => v.ToString(),
x => TimeSpan.Parse(x));
When I try to run this conversion I get the following error:
System.InvalidCastException: Unable to cast object of type 'System.TimeSpan' to type 'System.String'.
It seems like this should be straight forward.
Can someone help me understand what I am doing wrong??
PS: I also tried the build in:
var timeStringConverter = new TimeSpanToStringConverter();
entity.Property(e => e.PickupTime).HasConversion(timeStringConverter);
and I got the same error.
Thanks!
Looking at the reference documentation for ValueConverter
ConvertFromProvider
Gets the function to convert objects when reading data from the store, setup to handle nulls, boxing, and non-exact matches of simple types.
ConvertToProviderExpression:
Gets the function to convert objects when writing data to the store, setup to handle nulls, boxing, and non-exact matches of simple types.
So 'from', and 'to' are the point of view of the store, the database.
In the overload...
.HasConversion(v => v.ToString(), x => TimeSpan.Parse(x))
...the first expression parameter is named 'convertToProviderExpression', the second one 'convertFromProviderExpression'. That means that the conversion writes a TimeSpan
as string to the database and reads a string from the database and converts it into TimeSpan
. Therefore, the database field must be a string.
The exception you get occurs when the database field is a time
datatype. The converter expects a string, but receives a TimeSpan
. The standard error for any .Net method receiving the wrong type is the error you get. In this context that's a somewhat confusing error.