差异

2017-10-17 85 views
-1

我有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是不支持的实体。只支持初始化器,实体成员和实体导航属性。'

这是我在后端方法,我尝试采取从模型属性差异

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

我怎样才能正确地计算出它

+2

使用视图模型 - 该属性不应该是您的数据模型的一部分 –

+1

你在'Where'子句中使用'Difference'属性吗?如果是这样,您可以依赖System.Data.Entity.DbFunctions.Diff *函数之一而不是“差异”。 – jbl

+0

目前仍不清楚为何要在数据库级别计算差异。它是否涉及'OrderBy',并带有'Take?涉及coeff? – jbl

回答

4

的问题是,你正在使用的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评论:使用视图模型 - 该属性不应该是您的数据模型的一部分

+1

并且在没有添加的情况下,使用System.ComponentModel.DataAnnotations.Schema; –

+0

要增加这个美妙的答案,第二行是多余的; '日期时间? - DateTime?'已经返回'TimeSpan?',并且对'null'值正确工作(即返回'null')。 – decPL

+0

@decPL - ops true!谢谢。检查,你是正确的。已更新回答 –