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: 8719

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

Pam 30/08/2017 11:30
In response to Sending Email in Razor Pages
Mike, RazorPages sound like a nice choice for somebody still working in ASP classic who wants to to...

Robby Robson 15/08/2017 00:43
In response to Routing in Razor Pages
Mike: great stuff. Now that .Core Standard 2.0 is formally out, how soon will you rewrite your book...

Satyabrata Mohapatra 28/07/2017 08:59
In response to Sending Email in Razor Pages
Bit off topic, but congratulation sir for your MVP award. You deserve it !!!...

Satyabrata Mohapatra 23/07/2017 16:43
In response to Razor Pages - The Elevator Pitch
@Dale Severin You can continue to build apps using asp.net web pages....

Satyabrata Mohapatra 23/07/2017 16:40
In response to Sending Email in Razor Pages
Thanks for sharing...learned a lot...

Gfw 22/07/2017 11:53
In response to Sending Email in Razor Pages
Question... Does System.Net.Mail support SSL?...

Dale Severin 20/07/2017 03:38
In response to Razor Pages - The Elevator Pitch
I work with razor web pages extensively. I appreciate the rapid development it permits me to I am as...

Obinna Okafor 14/07/2017 01:19
In response to Routing in Razor Pages
Thank you, Mike. Good post....

Satyabrata Mohapatra 11/07/2017 16:02
In response to Routing in Razor Pages
Very powerful routing system!!...

Cyrus 05/07/2017 03:41
In response to Razor Pages - Getting Started With The Preview
How can I trim packages and services as much as possible to use just razor pages? I don’t want to to...