99823
99823

Reputation: 2457

Invalid cast from 'System.String' to 'System.TimeSpan' EF 4.1/MySql Connector/Net 6.4.4

For the life of me I cannot get this bug figured out - I have two time fields in mysql, properly mapping as Timestamp fields in ASP.net Entity Framework. I can assign and INSERT into the db no problem, however, whenever I try to load the data back out by simply querying the database I receive the following error message: Invalid cast from 'System.String' to 'System.TimeSpan'

        using (hydraEntities db = new hydraEntities())
        {

            Employer = db.employers.Include("address").Where(em => em.EmployerId == EmployerId).First();
        }

I cannot figure it out, i've upgraded the mysql connector to the latest release praying that would solve the bug - however that did not fix it. Any help would be GREATLY appreciated!

Upvotes: 0

Views: 1424

Answers (2)

undefined
undefined

Reputation: 34309

Ok so this post is about how people have approached storing the time of day. C# DateTime: What "date" to use when i'm using just the "time"?

its not really something that C# understands as such so anything is a bit of a work around. If you really want a timespan you would probably be best to store that as an int in the database for the number of ticks in the timespan, then convert it in your model.

Another option would just to be to store the hours/minutes components in a data structure of your own.

eg

public class TimeOfDay
{
    public int Hours{get;set;}
    public int Minutes{get;set;}

    //possibly even
    public TimeSpan TimeSpan
    {
        get
        {
            return new TimeSpan(new DateTime(2000,1,1,Hours,Minutes,0).Ticks -new DateTime(2000,1,1).Ticks);
        }
    }
}

Upvotes: 0

MethodMan
MethodMan

Reputation: 18863

Try something like this.. TimeSpan is a deals with Length perhaps you meant TimeStamp.. what ever the case if you did mean TimeSpan.. can you double check and clarify..?

TimeSpan would work.. here is a something you could use.. problem is you will need to figure out the milliseconds of what's in the timespan field to replace your milliseconds with what I have pasted in this code example

DateTime dt = new DateTime().Add( TimeSpan.FromMilliseconds( 1304686771794 ) ) 

Upvotes: 1

Related Questions