【发布时间】:2011-07-21 00:11:51
【问题描述】:
我想将我的编辑保存到数据库,并且我在 ASP.NET MVC 3 / C# 中使用实体框架代码优先,但我遇到了错误。在我的 Event 类中,我有 DateTime 和 TimeSpan 数据类型,但在我的数据库中,我分别有 Date 和 time。这可能是原因吗?在将更改保存到数据库之前,如何在代码中转换为适当的数据类型。
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:\sep\MvcEventCalendar\MvcEventCalendar\Controllers\EventManagerController.cs 行:77
堆栈跟踪:
[DbEntityValidationException:一个或多个实体的验证失败。有关详细信息,请参阅“EntityValidationErrors”属性。]
【问题讨论】:
-
您的必填字段之一可能为空值。比如 EventDate 、 StartTime 、 Price、 Category 等
-
您是否检查过要发布的表单变量以确保每个变量都与数据库定义的类型匹配?或者就像 Daveo 所说的那样,缺少所需的表单值之一......
-
并非所有发布的表单变量都与数据库定义的类型匹配。我在数据库中使用了日期和时间,但在 .NET 中没有等效的直接数据类型。因此,我使用了 DateTime 和 TimeSpan。现在我需要将两者分别转换为日期和时间。
-
我的错误来源是一个超过 30 个字符的字符串字段,我在数据库中的字段大小为 30。
标签: c# sql asp.net-mvc entity-framework code-first