Entity Framework Recipe: Storing And Managing Time

4.75 (8 votes)

This post explores the options available to you when your application requirements include managing and storing time using the Entity Framework. Specifically, I am thinking of durations of time, such as the time required to complete some kind of task, not the time part of a date. Relevant examples might include storing the length of a movie, or the preparation time required for a recipe.

The .NET data type that represents durations or intervals of time is a TimeSpan type. It has a variety of methods and properties that provide easy access to the constituent parts of the value, such as the days, hours, minutes, seconds etc. However, the Entity Framework maps the TimeSpan type to the time data type in SQL Server, which actually represents a point in time during a 24 hour period. They are not really analogous, and you cannot represent a time interval of greater than 24 hours using the SQL Server time data type. The TimeSpan type has a Ticks property, which is an Int64 (long), and maps to a bigint data type in SQL Server. It also has a constructor that accepts a long representing the number of Ticks, making it easy to convert longs to TimeSpans and vice-versa. Therefore it makes much more sense to use a long to represent a duration of time in ticks, as illustrated in the Duration property of the example Movie class, and store that in the database.

public class Movie
{
    public int MovieId { get; set; }
    public string Title { get; set; }
    public DateTime ReleaseDate { get; set; }
    public string Genre { get; set; }
    public long Duration { get; set; }
}

It would be unrealistic to ask users to provide a movie's duration in ticks when they submit a new movie or edit an existing one, so your interface should collect values representing the hours and minutes that make up the duration. Then you can use those to generate a TimeSpan value and save its Ticks property in the database. Here's a view model designed for a new movie form:

public class MovieFormModel
{
    public string Title { get; set; }
    public DateTime ReleaseDate { get; set; }
    public string Genre { get; set; }
    [Display(Name="Duration Hours")]
    public int DurationHours { get; set; }
    [Display(Name = "Duration Minutes")]
    public int DurationMinutes { get; set; }
    public IEnumerable<SelectListItem> Hours {
        get 
        { 
            return Enumerable.Range(0, 11)
                .Select(r => new SelectListItem
                {
                    Value = r.ToString(),
                    Text = r.ToString(),
                    Selected = r == DurationHours
                });
        }
    } 
    public IEnumerable<SelectListItem> Minutes{
        get
        {
            return Enumerable.Range(0, 59)
                .Select(r => new SelectListItem
                {
                    Value = r.ToString(),
                    Text = r.ToString(),
                    Selected = r == DurationMinutes
                });
        }
    } 
    public long Duration { 
        get { 
            return new TimeSpan(DurationHours, DurationMinutes, 0).Ticks; 
        }
    }
}

The Hours and Minutes properties provide the values for two dropdownlists. The DurationHours and DurationMinutes properties are used to represent the selected values from the dropdownlists. The Duration property will map to the movie's Duration property, and as mentioned before, it stores the value of the Ticks property of a TimeSpan object constructed from the selected hours and minutes. Here's a sample form that makes use of this view model:

@using (Html.BeginForm()) 
{
    @Html.AntiForgeryToken()
    
    <div class="form-horizontal">
        <h4>Movie</h4>
        <hr />
        @Html.ValidationSummary(true)

        <div class="form-group">
            @Html.LabelFor(model => model.Title, new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Title)
                @Html.ValidationMessageFor(model => model.Title)
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.ReleaseDate, new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.ReleaseDate)
                @Html.ValidationMessageFor(model => model.ReleaseDate)
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.Genre, new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Genre)
                @Html.ValidationMessageFor(model => model.Genre)
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.DurationHours, new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.DropDownListFor(model => model.DurationHours, Model.Hours)
                @Html.ValidationMessageFor(model => model.DurationHours)
            </div>
        </div>
        <div class="form-group">
            @Html.LabelFor(model => model.DurationMinutes, new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.DropDownListFor(model => model.DurationMinutes, Model.Minutes)
                @Html.ValidationMessageFor(model => model.DurationMinutes)
            </div>
        </div>
        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Create" class="btn btn-default" />
            </div>
        </div>
    </div>
}

EF Recipe TimeSpans

When the form is submitted, the values are mapped across to a new movie object and saved to a database:

[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Create(MovieFormModel model)
{
    if (ModelState.IsValid)
    {
        var movie = new Movie
        {
            Title = model.Title,
            Genre = model.Genre,
            ReleaseDate = model.ReleaseDate,
            Duration = model.Duration
        };
        db.Movies.Add(movie);
        await db.SaveChangesAsync();
        return RedirectToAction("Index");
    }
    return View(model);
}

When you want to display the movie object along with its duration, you construct a new TimeSpan object from the Ticks value stored in the database and can then access the Hours and Minutes properties of the TimeSpan object to produce the required display. Here's another view model designed for that purpose to illustrate the procedure:

public class MovieViewModel
{
    public int MovieId { get; set; }
    public string Title { get; set; }
    public DateTime ReleaseDate { get; set; }
    public string DateOfRelease 
    {
        get
        {
            return ReleaseDate.ToLongDateString();
        }
    }
    public string Genre { get; set; }
    public string DurationTime 
    { 
        get {
            var ts = new TimeSpan(Duration);
            var h = ts.Hours == 1 ? "hour" : "hours";
            var m = ts.Minutes == 1 ? "min" : "mins";
            return string.Format("{0} {1} {2} {3}", ts.Hours, h, ts.Minutes, m);
        } 
    }
    public long Duration { get; set; }
}

Notice how logic exists in both view models to prepare the values for ultimate display. This is one of the primary benefits of using view models; they help to keep both your controllers and views clear of formatting and presentation logic.

Summary

This brief article examined the problem of storing and displaying durations of time with the Entity Framework and SQL Server, and showed how you can use an Int64 (or long)for storage, and a TimeSpan object for display purposes.

You might also like...

Date Posted:
Last Updated:
Posted by:
Total Views to date: 7986

3 Comments

- Jerrie Pelser

Nice article Mike!

I think there is an error in the House property getter of MovieFormModel. Your code says:

Selected = r == DurationMinutes

Should that not be

Selected = r == DurationHours

And the same thing is also happening in the Minutes getter where you are looking at DurationHours instead of DurationMinutes.

Also why is it Enumerable.Range(0, 61)? Should it not be Enumerable.Range(0, 59)?

- Mike

@Jerrie,

You were right about the errors!. I've updated the article so that it makes a little more sense now. Thanks!

- Sarah

Hi Mike - thanks - I've been referring to your website for help in learning MVC.

Quick question - i'm struggling knowing how to edit the duration once it's added...

can you provide the edit functionality as an example

thanks, Sarah

Recent Comments

Cyrus 26/05/2017 06:00
In response to Razor Pages - The Elevator Pitch
There are some concern about razor pages performance. Is it faster or slower than MVC? would you a a...

Cyrus 26/05/2017 05:44
In response to Razor Pages - Understanding Handler Methods
well done, thank you....

Satyabrata Mohapatra 23/05/2017 11:41
In response to Razor Pages - Understanding Handler Methods
Nice and easy !! Great post....

Cyrus 16/05/2017 19:55
In response to Razor Pages - Getting Started With The Preview
There is something wrong related to microsoft.dotnetcore.mvc.taghelpers! if you remove it from page...

Cyrus 16/05/2017 10:18
In response to Razor Pages - Getting Started With The Preview
well done mike, it was very useful, I really appreciate that....

Satyabrata Mohapatra 16/05/2017 07:21
In response to Razor Pages - Getting Started With The Preview
Finally!!!! web pages in asp.net core!!! Super excited !!!! Thank u sir for sharing.....Awaiting on...

Daniele 14/03/2017 10:24
In response to Working With Zip Files In ASP.NET MVC
is it possible give to the user a progress bar of the zipping process? Thanks in advance. ...

Suraj 13/03/2017 22:20
In response to Working With Zip Files In ASP.NET MVC
Very nice article. Thanks....

Satyabrata Mohapatra 19/02/2017 03:01
In response to Free SSL Certificates On IIS With LetsEncrypt
Thanks for sharing. Learned a lot !!...

Gfw 03/02/2017 09:48
In response to Free SSL Certificates On IIS With LetsEncrypt
I have used WinSimple for about the last 9 months - works great. One thing that you want to make of...