我想将我的编辑保存到数据库,并且我在ASP.NET MVC 3/C#中使用实体框架代码优先,但我收到错误。在我的Event类中,我有DateTime和TimeSpan数据类型,但是在我的数据库中,分别有Date和Time。这可能是原因吗?在保存对数据库的更改之前,如何在代码中转换为适当的数据类型。使用实体框架保存对SQL Server数据库的更改时,一个或多个实体的验证失败
public class Event
{
public int EventId { get; set; }
public int CategoryId { get; set; }
public int PlaceId { get; set; }
public string Title { get; set; }
public decimal Price { get; set; }
public DateTime EventDate { get; set; }
public TimeSpan StartTime { get; set; }
public TimeSpan EndTime { get; set; }
public string Description { get; set; }
public string EventPlaceUrl { get; set; }
public Category Category { get; set; }
public Place Place { get; set; }
}
控制器中的方法>>>>问题在storeDB.SaveChanges();在 '/' 应用
// POST: /EventManager/Edit/386
[HttpPost]
public ActionResult Edit(int id, FormCollection collection)
{
var theEvent = storeDB.Events.Find(id);
if (TryUpdateModel(theEvent))
{
storeDB.SaveChanges();
return RedirectToAction("Index");
}
else
{
ViewBag.Categories = storeDB.Categories.OrderBy(g => g.Name).ToList();
ViewBag.Places = storeDB.Places.OrderBy(a => a.Name).ToList();
return View(theEvent);
}
}
与
public class EventCalendarEntities : DbContext
{
public DbSet<Event> Events { get; set; }
public DbSet<Category> Categories { get; set; }
public DbSet<Place> Places { get; set; }
}
的SQL Server 2008 R2数据库/ T-SQL
EventDate (Datatype = date)
StartTime (Datatype = time)
EndTime (Datatype = time)
HTTP表单
EventDate (Datatype = DateTime) e.g. 4/8/2011 12:00:00 AM
StartTime (Datatype = Timespan/time not sure) e.g. 08:30:00
EndTime (Datatype = Timespan/time not sure) e.g. 09:00:00
服务器错误。
一个或多个实体的验证失败。有关更多详细信息,请参阅“EntityValidationErrors”属性。
描述:执行当前Web请求期间发生未处理的异常。请查看堆栈跟踪以获取有关该错误的更多信息以及源代码的位置。
异常详细信息:System.Data.Entity.Validation.DbEntityValidationException:一个或多个实体的验证失败。有关更多详细信息,请参阅“EntityValidationErrors”属性。
源错误:
Line 75: if (TryUpdateModel(theEvent))
Line 76: {
Line 77: storeDB.SaveChanges();
Line 78: return RedirectToAction("Index");
Line 79: }
源文件:C:\月\ MvcEventCalendar \ MvcEventCalendar \ \控制器线路EventManagerController.cs:77
堆栈跟踪:
[DbEntityValidationException:验证失败对于一个或多个实体。有关更多详细信息,请参阅“EntityValidationErrors”属性。]
可能您的一个必填字段为空值。像EventDate,StartTime,价格,类别等 – Daveo 2011-03-23 04:00:26
您是否检查了发布的表单变量以确保每个匹配数据库定义的类型?或者像Daveo所说的那样,缺少所需的表单值之一... – timothyclifford 2011-03-23 04:40:28
并非所有发布的表单变量都与数据库定义的类型相匹配。我在数据库中使用了日期和时间,但在.NET中没有直接的数据类型。因此,我使用了DateTime和TimeSpan。现在我需要将这两者分别转换为日期和时间。 – user522767 2011-03-23 04:51:17