Sign up ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

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;
    }
}
share|improve this question

1 Answer 1

up vote 1 down vote accepted

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)
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.