Serialize the properties of an entity framework entity to data fields and back I am trying to write code to convert properties of an Entity Framework entity to strings and back.

Here is the code so far that converts back from strings to the object properties.

I am stuck trying to figure out how to handle datetime.  I am also wondering if there is a better approach.

private static FormatterConverter formatConverter;
public static FormatterConverter FormatConverter
{
    get
    {
        if (formatConverter == null)
        {
            formatConverter = new FormatterConverter();
        }
        return formatConverter;
    }
}

// ChangeValue is an entity framework entity.
static void DoSetValue(ChangeValue cv , PropertyInfo pi, object obj )
{
    try
    {
        switch (pi.PropertyType.ToString())
        {
            case "System.TimeSpan":
            case "System.Nullable`1[System.TimeSpan]":
                var s = cv.Value;
                if (s == "") s = "0";
                var ticks = Convert.ToInt64(s);
                var ts = new TimeSpan(ticks);
                obj = ts;
                break;
            case "":
            case "System.Nullable`1[System.DateTime]":
                // code needed here
                break;
            case "System.Guid":
                obj = new Guid(cv.Value);
                break;
            default:
                pi.SetValue(obj,  FormatConverter.Convert(cv.Value, pi.PropertyType), null);
                break;
        }
    }
    catch (Exception ex)
    {
        ex.Data.Add("", string.Format( "Error converting type for {0} {1} ",pi.Name ,pi.PropertyType.ToString()));
        throw ex;
    }
}
If you are trying to convert the string to DateTime format that might be used in the EF object, you may try:

Convert.ToDateTime("2013-09-10 12:12:12",System.Globalization.CultureInfo.InvariantCulture)