简体   繁体   中英

Difference between two datetime properties in model (c#)

I have model with 2 DateTime properties

Here is code

    sing System.ComponentModel.DataAnnotations.Schema;

namespace GoogleMapsAsp_Net.Models
{
    using System;
    using System.Collections.Generic;

    public partial class Park
    {
        public int parkId { get; set; }
        public decimal Longitude { get; set; }
        public decimal Latitude { get; set; }
        public Nullable<System.DateTime> TimeStart { get; set; }
        public Nullable<System.DateTime> TimeEnd { get; set; }
        [NotMapped]
        public TimeSpan? Difference { get { return TimeStart - TimeEnd; } }
    }
}

I want to calculate difference between them in minutes and write difference in new property. So I wrote this property

public TimeSpan? Difference { get { return TimeStart - TimeEnd; } }

But when I run project I have this error

'The specified type member 'Difference' is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties are supported.'

Here is my method on back end where I try to take difference from model property

public JsonResult GetPlaces()
    {
        using (var ctx = new GoogleMapsAsp_NetContext())
        {
             const int coeff = 2; 
            var items = ctx.Parks.Select(
                x => new
                {
                    lng = x.Longitude,
                    lat = x.Latitude,
                    difference = x.Difference
                }
            ).ToList();
            return Json(items.ToArray(), JsonRequestBehavior.AllowGet);
        }
    }

How I can calculate it correctly

The problem is that you are using the Distance property in the query that is executed in the database, which is not possible. Add AsEnumerable to bring the data before using the property:

var items = ctx.Parks.AsEnumerable().Select(
            x => new {
                lng = x.Longitude,
                lat = x.Latitude,
                difference = x.Difference
            }).ToArray();

No need to first create it as a List and then call ToArray . Just use ToArray once


Previously irrelevant answered: Use the [NotMapped] attribute so EF ignores the property:

[NotMapped]
public TimeSpan? Difference { get { return TimeStart - TimeEnd; } }

Or better still as @Stephen commented: Use a view model - that property should not be part of your data model

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM