Entity Framework 5.0 and Timespan type

Entity Framework version 5, like its previous version doesn’t map timespan. The following error will raise when you try to.

There is no store type corresponding to the conceptual side type ‘Edm.Time(Nullable=True,DefaultValue=,Precision=)’ of primitive type ‘Time’.

I thought that Entity Framework 5 was able with SQL Server 2008 R2 to map Timespan to Time. I was wrong. However, theirs a work around.

public Int64 TimeBetweenExercicesTicks{ get; set; }

public TimeSpan TimeBetweenExercices
    get { return TimeSpan.FromTicks(TimeBetweenExercicesTicks); }
    set { TimeBetweenExercicesTicks= value.Ticks; }

First, you should want to still use in your code the TimeSpan type because it’s convenient to manipulate time. But, on the other side Entity Framework doesn’t map the type. Fortunately, we can map the ticks and simply ignore the property with the TimeSpan type.

The example above show you this scenario where an entity required to have the time between two exercices. In fact, the TimeBetweenExercices is not mapped to the database but the underlying property TimeBetweenExercicesTicks. Since an Int64 can be mapped and that we do not loss any precision by converting ticks to/from timespan, that we can use this time.

If you like my article, think to buy my annual book, professionally edited by a proofreader. directly from me or on Amazon. I also wrote a TypeScript book called Holistic TypeScript

3 thoughts on “Entity Framework 5.0 and Timespan type

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.