【发布时间】:2015-05-04 19:12:53
【问题描述】:
我想在我的数据库中选择可用的 spotId。我有这个方法:
public ActionResult ShowAvailableSpots(int Id, DateTime ArrivalDate, DateTime LeaveDate)
{
var query2 = (from r in db.Reservations
where (DbFunctions.TruncateTime(r.ArrivalDate) >= DbFunctions.TruncateTime(ArrivalDate)
&& DbFunctions.TruncateTime(r.LeaveDate) <= DbFunctions.TruncateTime(LeaveDate))
select r.spot);
ViewBag.StartingDate = ArrivalDate;
ViewBag.EndingDate = LeaveDate;
ViewBag.AvailableSpots = query2;
ViewBag.CampingSpotId = new SelectList(query2, "CampingSpotId", "SpotName");
return View();
}
我确定在给定的日期范围内没有预订,那为什么没有返回 Spot id?
查询生成的输出如下:
SELECT
[Extent2].[campingspotid] AS [CampingSpotId],
[Extent2].[spotname] AS [SpotName],
[Extent2].[fieldname] AS [FieldName],
[Extent2].[surface] AS [Surface],
[Extent2].[wifi] AS [Wifi],
[Extent2].[water] AS [Water],
[Extent2].[sewer] AS [Sewer],
[Extent2].[reserved] AS [Reserved],
[Extent2].[booked] AS [Booked],
[Extent2].[spotprice] AS [SpotPrice],
[Extent2].[type] AS [Type]
FROM
[dbo].[reservations] AS [Extent1]
INNER JOIN
[dbo].[campingspots] AS [Extent2]
ON [Extent1].[campingspotid] = [Extent2].[campingspotid]
WHERE
(
(
CONVERT (DATETIME2, CONVERT(VARCHAR(255), [Extent1].[arrivaldate], 102), 102 )
) >= (
CONVERT (DATETIME2, CONVERT(VARCHAR(255), @p__linq__0, 102), 102 )
)
)
AND (
(
CONVERT (DATETIME2, CONVERT(VARCHAR(255), [Extent1].[leavedate], 102), 102)
) <= (
CONVERT (DATETIME2, CONVERT(VARCHAR(255), @p__linq__1, 102 ), 102)
)
)
PS:我使用 TruncateTime 是因为 this
编辑:这是我的预订模型:
public class Reservation
{
[Key]
public int ReservationId { get; set; }
[DataType(DataType.Date)]
public DateTime ArrivalDate { get; set; }
[DataType(DataType.Date)]
public DateTime LeaveDate { get; set; }
//Vreemdesleutel van Plek
public int CampingSpotId { get; set; }
public virtual CampingSpot spot { get; set; }
}
这是我的露营地模型:
public class CampingSpot
{
[Key]
[Required(ErrorMessage = "Please select at least one CampingSpotID")]
public int CampingSpotId { get; set; }
public string SpotName { get; set; }
}
新的查询输出如下所示:SELECT CAST(NULL AS int) AS [C1], CAST(NULL AS datetime2) AS [C2], CAST(NULL AS datetime2) AS [C3], CAST(NULL AS int) AS [C4], CAST(NULL AS int) AS [C5], CAST(NULL AS int) AS [C6] FROM ( SELECT 1 AS X ) AS [SingleRowTable1] WHERE 1 = 0
上面的输出是由这个查询生成的:
var res = db.Reservations.Where(c => DbFunctions.TruncateTime(c.ArrivalDate) >= DbFunctions.TruncateTime(ArrivalDate)
&& DbFunctions.TruncateTime(c.LeaveDate) <= DbFunctions.TruncateTime(LeaveDate)
&& c.CampingSpotId == null);
【问题讨论】:
-
不要将“实时”
IQueryable对象传递给您的ViewBag/ViewModel/ViewData,而是在控制器的 Action 方法中执行查询并将实例化的结果传递给视图。 -
对于查询本身,从 MySQL Workbench 中运行它,看看它给出了什么结果。也就是说,生成的 SQL 在我看来不像 MySQL 的方言。您使用的是什么 DBMS?
-
它是 LINQ 转换为 SQL。我使用 Visual Studio 2013 来生成和管理数据库。
-
如果 VS 为您生成数据库,那么您将使用 Microsoft SQL Server,而不是 MySQL Server。为什么这个问题被标记为 MySQL Server?
-
糟糕 :) 为你更改了标签
标签: c# asp.net sql-server linq asp.net-mvc-5