1
\$\begingroup\$

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;
 }
}
Jamal
35.2k13 gold badges134 silver badges238 bronze badges
asked Sep 15, 2013 at 1:17
\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

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)
Jamal
35.2k13 gold badges134 silver badges238 bronze badges
answered Oct 13, 2013 at 18:28
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.