【发布时间】:2014-10-21 16:49:30
【问题描述】:
我只是 C#、MVC4、razor 和 Linq 的初级程序员。现在我正忙着为一个不存在的酒店构建一个应用程序。并且该应用程序几乎可以正常工作。但是有一个小错误。创建预订时,我想将房间和客人列表链接到预订。但是每次我创建一个新的预订时,都会在数据库中创建一个新的房间,其中除了 id 之外一切都是一样的。对于客人来说也是一样的,如果我创建一个新的预订,客人也会在数据库中创建并且不链接到预订。我已经使用了调试器和对象 Room,并且列表完美地传递给了预订的创建。所以在我的预订创建方法中一定有问题。我无法找出我的 Create 方法有什么问题。所以我希望能在这里找到一些帮助。任何帮助将不胜感激。
其他信息: TempStore 是一个静态类,我在其中临时保存了一些变量。
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(Booking booking)
{
if (ModelState.IsValid)
{
if (TempStore.tempGuests.Count == 0 || TempStore.tempRoom == null)
{
ModelState.AddModelError("NoGuestsSelected", "Please select the persons for your room.");
ModelState.AddModelError("NoRoomSelected", "Please select a room for your booking.");
return View();
}
else
{
booking.Room = TempStore.tempRoom;
booking.Guests = TempStore.tempGuests;
booking.PriceTotal = TempStore.priceTotal;
booking.AveragePrice = TempStore.averagePrice;
booking.StartDate = TempStore.startDate;
booking.EndDate = TempStore.endDate;
db.Bookings.Add(booking);
db.SaveChanges();
//Clearing the TempStore cause everything has been added
TempStore.tempGuests.Clear();
TempStore.tempRoom = null;
return RedirectToAction("Index");
}
}
return View(booking);
}
这是我的临时仓库
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Hotel.Models
{
public static class TempStore
{
public static Room tempRoom;
public static ICollection<Guest> tempGuests = new List<Guest>();
public static DateTime startDate;
public static DateTime endDate;
public static decimal priceTotal;
public static decimal averagePrice;
}
}
这是我设置客人的地方
public ActionResult AddGuest(int id)
{
Guest g = db.Guests.Find(id);
if (TempStore.tempGuests.Count != 0)
{
foreach (Guest gue in TempStore.tempGuests)
{
if (gue == g)
{
ModelState.AddModelError("DuplicateGuest", "Cannot select the same guest twice.");
return RedirectToAction("SelectGuest");
}
}
}
TempStore.tempGuests.Add(g);
return RedirectToAction("SelectGuest");
}
这是我为预订设置房间的地方:
public ActionResult AddRoom(int id)
{
Room r = db.Rooms.Find(id);
TempStore.tempRoom = r;
return RedirectToAction("SelectGuest");
}
【问题讨论】:
-
是创建重复房间的错误吗?另外,需要更多信息。 Booking的属性是什么?什么是 TempStore?
-
我认为问题在于 TempStore 如何创建房间。你能发布 TempStore 代码吗?
-
@user1666620:错误是创建了重复的房间和重复的用户。预订不包含任何属性。
-
@RufusL 我按照你的要求发布了我的 TempStore。
-
我一定错过了什么。没有填充 TempStore.Room 属性?此行:
booking.Room = TempStore.tempRoom;是否等同于:booking.Room = null;?
标签: c# linq asp.net-mvc-4 razor local-database