1

I am in the process of learning ASP.NET and MVC with Entity Framework, which is why this question may seem trivial to some of you.

My objective is relatively simple: I have a model (Hour.cs) like this:

public class Hour
{
    public int ID { get; set; }
    public int UsrID { get; set; }
    [DataType(DataType.Time)]
    [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:HH:mm}")]
    public DateTime StartDateTime { get; set; }
    [DataType(DataType.Time)]
    [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:HH:mm}")]
    public DateTime EndDatetime { get; set; }
    public int? ProjectID { get; set; }
    public virtual Project Project { get; set; }
    public virtual Usr Usr { get; set; }
}

I currently have a view that shows information in a table/list: StartDateTime,EndDateTime, UsrID, ProjectID

I want to add a column for TotalHrs represented by the difference between StartDateTime and EndDateTime.

To get the difference I have read numerous articles telling me to use timespan somewhere in the lines of:

Timspan diff = StartDateTime - EndDateTime;

What I do not understand is where to insert this code. I am assuming it is in the controller, but I do no understand how. My Index method looks like this:

public ActionResult Index()
    {
        var hours = db.Hours
            .Include(c => c.Usr)
            .Include(p => p.Project);

                   return View(hours.ToList());
    }

Any pointers appreciated!

1
  • What do you intend to do with the difference?
    – Jasen
    Apr 26, 2017 at 20:58

1 Answer 1

1

I would oppose to store such calculation on the database, when you can easily do it on client side as you have all the necessary information.

Add a new property and specify just a get accesor:

public class Hour
{
   // ...
   [NotMapped]
   public TimeSpan TotalHrs
   {
       get
       {
           return this.StartDateTime - this.EndDatetime;
       }
   }
   // ...
}

Then you can just access it like any other property in your view, controller or any class that consumes it.

TimeSpan val = hour.TotalHrs;
1
  • Just a note that TotalHrs can not be used in an EF/Linq-2-Sql query. The LINQ statement must be Linq-2-Objects (It needs to operate on an Enumerable as opposed to a Queryable).
    – James Haug
    Apr 27, 2017 at 14:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.