0

Entity Framework 4 . MySQL

I'm trying to map a varchar column to a class's DateTime property

my class:

[Table("webnews_in")]
public class WEBNews_in : AbsNews
{
    private DateTime _inDateTimeAdded = DateTime.MinValue;

    public DateTime InDateTimeAdded
    {
        get { return _inDateTimeAdded; }
        set { _inDateTimeAdded = value; }
    }

    private DateTime _inDateTimeUpdated = DateTime.MinValue;

    public DateTime InDateTimeUpdated
    {
        get { return _inDateTimeUpdated; }
        set { _inDateTimeUpdated = value; }
    }
}

CREATE TABLE webnews_in
    (
    Id                INT NOT NULL auto_increment,
    VPN_AC              VARCHAR (20) NULL,
    InDateTimeAdded   VARCHAR (50) NULL,
    InDateTimeUpdated VARCHAR (50) NULL

    PRIMARY KEY (Id)
    );

I got this error:

    Input string was not in a correct format. 
    Message Input string was not in a correct format. 
    Data IDictionary (0 items) 


StackTrace    at System.Number.StringToNumber(String str, NumberStyles options, NumberBuffer& number, NumberFormatInfo info, Boolean parseDecimal)
   at System.Number.ParseInt32(String s, NumberStyles style, NumberFormatInfo info)
   at MySql.Data.Types.MySqlDateTime.ParseMySql(String s)
   at MySql.Data.MySqlClient.MySqlDataReader.GetDateTime(Int32 i)
   at MySql.Data.Entity.EFMySqlDataReader.GetDateTime(Int32 ordinal) 
HelpLink null  
Source mscorlib 
Scott 混合理论
  • 2,263
  • 8
  • 34
  • 59

1 Answers1

2

EF throws error each time you set a type in the model that is diferent from the table, ie, if you set a field as integer in model, but this field have a type of string in the table, then in the load of data it will give you an error. To avoid it you have to make a workaround, declaring a public property with the table type equivalent and transforming it into the model desired type, try something like this:

[Table("webnews_in")]
public class WEBNews_in : AbsNews {

   private DateTime _inDateTimeAdded = DateTime.MinValue;

   public string InDateTimeAdded {
       get {
           return Format(_inDateTimeAdded, " dd/MM/yyyy hh:mm:ss tt");
       }
       set {
           _inDateTimeAdded = DateTime.Parse(value);
       }
   }

   private DateTime _inDateTimeUpdated = DateTime.MinValue;

   public string InDateTimeUpdated {
       get {
           return Format(_inDateTimeUpdated, " dd/MM/yyyy hh:mm:ss tt");
       }
       set {
           _inDateTimeUpdated = DateTime.Parse(value);
       }
   }
}
Henry Rodriguez
  • 805
  • 7
  • 11