我的项目中有模型。这是模型代码
public partial class Logging
{
public string Imei { get; set; }
public DateTime CurDateTime { get; set; }
public Nullable<System.DateTime> GPSDateTime2 { get; set; }
public Nullable<decimal> Latitude2 { get; set; }
public Nullable<decimal> Longitude2 { get; set; }
public string Speed { get; set; }
public Nullable<int> Datatype { get; set; }
public int Id { get; set; }
[NotMapped]
public TimeSpan? FirstStartDifference
{
get
{
if (CurDateTime != null)
{
var midnight = new DateTime(CurDateTime.Year, CurDateTime.Month, CurDateTime.Day, 00, 00, 00);
var difference = CurDateTime - midnight;
return difference;
}
return null;
}
}
[NotMapped]
public TimeSpan? LastStartDifference
{
get
{
if (CurDateTime != null)
{
var midnight = new DateTime(CurDateTime.Year, CurDateTime.Month, CurDateTime.Day, 23, 59, 00);
var difference = midnight - CurDateTime;
return difference;
}
return null;
}
}
[NotMapped]
public int coeff = 2;
}
我需要从数据库中获取一些项目,它是第一个条目,其中 Datatype==1
最后在哪里 Datatype ==2
.
所以我把这个方法写在后端
public JsonResult GetStops()
{
using (var ctx = new GoogleMapTutorialEntities())
{
var firstitem = ctx.Loggings.Where(x => x.Datatype == 2).AsEnumerable().Select(
x => new
{
lng = x.Longitude2,
lat = x.Latitude2,
difference = (int)(x.FirstStartDifference?.TotalMinutes ?? -1) * x.coeff
}).FirstOrDefault();
var lastItem = ctx.Loggings.Where(x => x.Datatype == 2).AsEnumerable().Select(
x => new
{
lng = x.Longitude2,
lat = x.Latitude2,
difference = (int)(x.LastStartDifference?.TotalMinutes ?? -1) * x.coeff
}).LastOrDefault();
List<Logging> items = new List<Logging> {firstitem, lastItem};
return Json(firstitem, JsonRequestBehavior.AllowGet);
}
}
在此之后我需要添加 firstitem
和 lastitem
列出。
我是这样写的List<Logging> items = new List<Logging> {firstitem, lastItem};
但是我得到一个错误
Severity Code Description Project File Line Suppression State Error CS1950 The best overloaded Add method 'List.Add(Logging)' for the collection initializer has some invalid arguments Heatmap C:\Users\nemes\source\repos\Heatmap\Heatmap\Controllers\HomeController.cs 37 Active Severity Code Description Project File Line Suppression State Error CS1503 Argument 1: cannot convert from '' to 'Heatmap.Models.Logging' Heatmap C:\Users\nemes\source\repos\Heatmap\Heatmap\Controllers\HomeController.cs 37 Active
为此List<Logging> items = new List<Logging> {firstitem, lastItem};
如何将它们添加到列表中?
最佳答案
您正在返回一个匿名类型而不是 Logging
。 firstitem
和 lastItem
是 Anonymous Types .将您的代码更改为:
x => new Logging
{
Longitude2 = x.Longitude2,
Latitude2 = x.Latitude2,
//And other properties
}
如果您仍然遇到错误,可能是因为您无法投影到映射的实体上,那么您需要创建一个 DTO具有 Logging
实体中所需属性的类:
public class LoggingDTO
{
public string Longitude2 { get; set; }
public string Latitude2 { get; set; }
//And other properties
}
然后:
x => new LoggingDTO
关于c# - 如何将项目添加到列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46905392/