简体   繁体   English

模型(C#)中两个日期时间属性之间的差异

[英]Difference between two datetime properties in model (c#)

I have model with 2 DateTime properties 我有2个DateTime属性的模型

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. LINQ to Entities不支持'指定类型成员'Difference'。 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. 问题在于您无法在数据库中执行的查询中使用Distance属性。 Add AsEnumerable to bring the data before using the property: 添加AsEnumerable以在使用属性之前带来数据:

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 . 无需先将其创建为List ,然后调用ToArray Just use ToArray once 只需使用一次ToArray


Previously irrelevant answered: Use the [NotMapped] attribute so EF ignores the property: 以前不相关的答案:使用[NotMapped]属性,以便EF忽略该属性:

[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 还是更好,就像@Stephen评论的那样: 使用视图模型-该属性不应成为数据模型的一部分

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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