Trying to convert TimeSpan to a String using a valueconverter in .net core

.net-core asp.net-core entity-framework-core

Question

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!

1
1
8/28/2019 5:13:50 PM

Accepted Answer

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.

1
8/30/2019 11:50:16 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow