【发布时间】:2018-04-03 05:03:39
【问题描述】:
您好,我正在尝试比较来自 2 个模型的两个共享数据类型值:
目标 -
public int Id { get; set; }
public DateTime StartDate { get; set; }
public DateTime? EndDate { get; set; }
public string Type { get; set; }
public double Level { get; set; }
public bool Achieved { get; set; }
和 距离:
public class Distance
{
public int Id { get; set; }
public double DistanceRun { get; set; }
public DateTime _Date { get; set; }
public String AdditionalComments { get; set; }
}
这是我的代码,用于比较两个日期(目标)之间的距离。
public ActionResult AchievedGoals(string type)
{
var goals = db.Goals.Where(x => x.EndDate != null).AsEnumerable();
List<Distance> distances = new List<Distance>();
foreach (var goal in goals)
{
var goalsBetween = db.Distances.Where(x => x._Date.Date.CompareTo(goal.StartDate) > 0 & x._Date.Date.CompareTo(goal.EndDate) < 0);
Distance d = (Distance) goalsBetween;
distances.Add(d);
}
return View(distances.ToList());
}
我收到一个错误
Distance d = (Distance) goalsBetween;
表示此错误的行
System.InvalidCastException: '无法将'System.Data.Entity.Infrastructure.DbQuery`1[WAD_Tracker.Models.Distance]'类型的对象转换为'WAD_Tracker.Models.Distance'类型。'
这也是视图:
@model IEnumerable<WAD_Tracker.Models.Goals>
@{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Index</h2>
<p>
@Html.ActionLink("Create New", "Create")
</p>
<table class="table">
<tr>
<th>
@Html.DisplayNameFor(model => model.StartDate)
</th>
<th>
@Html.DisplayNameFor(model => model.EndDate)
</th>
<th>
@Html.DisplayNameFor(model => model.Type)
</th>
<th>
@Html.DisplayNameFor(model => model.Level)
</th>
<th>
@Html.DisplayNameFor(model => model.Achieved)
</th>
<th></th>
</tr>
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.StartDate)
</td>
<td>
@Html.DisplayFor(modelItem => item.EndDate)
</td>
<td>
@Html.DisplayFor(modelItem => item.Type)
</td>
<td>
@Html.DisplayFor(modelItem => item.Level)
</td>
<td>
@Html.DisplayFor(modelItem => item.Achieved)
</td>
<td>
@Html.ActionLink("Edit", "Edit", new { id=item.Id }) |
@Html.ActionLink("Details", "Details", new { id=item.Id }) |
@Html.ActionLink("Delete", "Delete", new { id=item.Id })
</td>
</tr>
}
</table>
【问题讨论】:
-
您正在尝试将距离集合投射到距离。您可以尝试使用 db.Distances.where(yourcondition).FirstOrDefault() 来获取一行距离
标签: c# asp.net-mvc linq asp.net-mvc-5