[英]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.