繁体   English   中英

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

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

我有2个DateTime属性的模型

这是代码

    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; } }
    }
}

我想在几分钟内计算它们之间的差异,并在新属性中写入差异。 所以我写了这个财产

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

但是当我运行项目时出现此错误

LINQ to Entities不支持'指定类型成员'Difference'。 仅支持初始化程序,实体成员和实体导航属性。

这是后端的方法,在这里我尝试与模型属性区别

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);
        }
    }

如何正确计算

问题在于您无法在数据库中执行的查询中使用Distance属性。 添加AsEnumerable以在使用属性之前带来数据:

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

无需先将其创建为List ,然后调用ToArray 只需使用一次ToArray


以前不相关的答案:使用[NotMapped]属性,以便EF忽略该属性:

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

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

暂无
暂无

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

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