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.

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

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

Thomas 05/03/2018 00:59
In response to I'm Not Writing A Book On Razor Pages
There's a typo on this page: = true)] should be [BindProperty(SupportsGet = true)]...

Rolf Herbert 04/03/2018 19:25
In response to I'm Not Writing A Book On Razor Pages
So is MS deprecating razor Web Pages..? Is it dead..? I wish they would stop killing things so its...

Borut 17/02/2018 12:59
In response to I'm Not Writing A Book On Razor Pages
Mike, is it possible that Web Pages and Razor Pages "live" together in one web application? I a I...

hrboyce 09/02/2018 04:44
In response to I'm Not Writing A Book On Razor Pages
Mike, First thanks for doing this but I have to ask, any chance you would consider converting one of...

aziz sallam 07/02/2018 10:18
In response to I'm Not Writing A Book On Razor Pages
u are a great man...

Satyabrata Mohapatra 31/01/2018 11:36
In response to I'm Not Writing A Book On Razor Pages
This is a great news!!!! Thanks...

tangdf 30/01/2018 07:25
In response to I'm Not Writing A Book On Razor Pages
=> { o.ConfigureFilter(new IgnoreAntiforgeryTokenAttribute()); }); The extension method does...

Obinna Okafor 30/01/2018 04:02
In response to I'm Not Writing A Book On Razor Pages
Thank you very much. I would like to see a project built from scratch using Razor Pages. And it show...

rachida Dukes 31/10/2017 13:52
In response to Customising Identity in Razor Pages
Thanks again for this wonderful tutorial. I followed all the steps in this section called: Adding...

Rachida 31/10/2017 12:06
In response to Customising Identity in Razor Pages
Thanks very much for this wonderful tutorial, it helped a lot....