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

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

Sivu 19/10/2016 08:21
In response to Entity Framework Core TrackGraph For Disconnected Data
Oh that's very very very nice ! Thanks for the write up Mike, much appreciated for the taking the to...

Mark 12/10/2016 16:42
In response to ASP.NET Web Pages vNext or Razor Pages
Although "Web Pages" was removed from the roadmap, has it just been renamed to "Razor Pages"?...

Satyabrata 12/10/2016 09:20
In response to Entity Framework Core TrackGraph For Disconnected Data
Nice article. Please write more articles featuring ASP.Net web pages. Thank you...

Julian 26/09/2016 14:27
In response to Loading ASP.NET Core MVC Views From A Database Or Other Location
Fantastic, many thanks Mike! Had got half way down this road before finding your article - saved...

Abolfazl Roshanzamir 14/09/2016 05:36
In response to Loading ASP.NET Core MVC Views From A Database Or Other Location
Nice article. Thanke you so much ....

cyrus 02/09/2016 15:12
In response to ASP.NET Web Pages vNext or Razor Pages
I've got some news. As Damian stated in this link: https://github.com/aspnet/Mvc/issues/5208 “We...

Simon 01/09/2016 08:00
In response to Loading ASP.NET Core MVC Views From A Database Or Other Location
Thanks Mike, nice post and exactly what I was looking for. Like you said, I think I'll opt to the...

dave 20/08/2016 14:57
In response to ASP.NET Web Pages vNext or Razor Pages
Do SimplemembershipProvider in viewpages is supported?...

Steven 18/08/2016 04:40
In response to Entity Framework Code First and Stored Procedures
Can you provide the directives (using statements) you're using for EF7 example?...

yousaid 17/08/2016 22:08
In response to ASP.NET Web Pages vNext or Razor Pages
Increasingly, learning a Microsoft tool is no longer worth the return on investment. Too many tools...