尝试将项目添加到数据库上下文时出现以下错误。我在 Web API 项目中使用实体框架。示例代码如下所示。
例外
System.Data.Entity.Infrastructure.DbUpdateException
HResult=0x80131501 消息=更新条目时出错。有关详细信息,请参阅内部异常。Source=EntityFramework StackTrace:在 System.Data.Entity.Internal.InternalContext.SaveChanges() 在 System.Data.Entity.Internal.LazyInternalContext.SaveChanges() 在 System.Data.Entity.DbContext.SaveChanges() 在 WebApiSample.Controllers。 OrdersController.Orders(Order neworder) in C:\Repository\bitbucket\OtherProjects\WebApiSample\WebApiSample\Controllers\OrdersController.cs:line 173 at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.<>c__DisplayClass10.b__9( , Object[] methodParameters) 在 System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.Execute(Object instance, Object[] arguments) 在 System.Web.Http.Controllers。内部异常 1:UpdateException:更新条目时出错。有关详细信息,请参阅内部异常。
内部异常 2:SqlException:无法将值 NULL 插入列 'OrderNumber',表 'C:\REPOSITORY\BITBUCKET\OTHERPROJECTS\WEBAPISAMPLE\WEBAPISAMPLE\APP_DATA\DATA.MDF.dbo.Orders';列不允许空值。插入失败。该语句已终止。
此代码是用 Web API 中的 POST 方法编写的:
[HttpPost]
public IHttpActionResult Orders(Order neworder)
{
if (neworder == null)
{
return BadRequest();
}
string uri = Url.Link("DefaultApi", new { id = neworder.OrderNumber });
try
{
using (OrderContext db = new OrderContext("ConnectionString"))
{ …Run Code Online (Sandbox Code Playgroud) c# entity-framework asp.net-web-api entity-framework-6 asp.net-web-api2