Entity Framework Recipe: Storing And Managing Time

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.