2010-03-01 92 views
0

嗨我遇到了解决这个错误的麻烦。对这个问题的任何帮助将不胜感激,谢谢!插入使用LINQ到实体

错误消息:

商店更新,插入或删除语句影响的行(0)的一个意想不到的数量。自实体加载后,实体可能已被修改或删除。刷新ObjectStateManager条目。

每当我尝试添加一个笔记本电脑/桌面,我收到上述错误信息。
在本地运行时,一切正常,但不在开发。网站和服务/数据库位于两个不同的开发箱中。

Tables: 
Computer: ComputerID, UserID, HardwareName, Brand, IsDefaultDevice 
Desktop: ComputerID, MonitorWidth 
Laptop: ComputerID, BatteryLife 

generated sql: 
exec sp_executesql N'insert [ScratchPad].[Computer]([UserID], [ComputerName], [Brand], [IsDefaultDevice]) 
values (@0, @1, @2, @3) 
select [ComputerID] 
from [ScratchPad].[Computer] 
where @@ROWCOUNT > 0 and [ComputerID] = scope_identity()',N'@0 bigint,@1 nvarchar(19),@2 int,@3 bit',@0=2,@1=N'Computer666',@2=1,@3=0 


using(var context = new MyDatabaseEntities()) 
{ 
     User user = context.Users.FirstOrDefault(x => x.UserID == userId); 
     entityToAdd.User = user; 
     bool hasOthers = context.Computers.Any(x=>x.User.UserID == userId); 
     if(!hasOthers && !entityToAdd.IsDefaultDevice) 
      entityToAdd.IsDefaultDevice = true; 
     entityToAdd.BrandReference.EntityKey = Brand.GetDellProviderKey(); 
     context.AddToComputers(entityToAdd); 
     context.SaveChanges(); 
} 

这里是堆栈跟踪:

被当前 web请求的执行期间产生的 未处理的异常。有关 原点和例外情况 的信息可以使用下面的例外 堆栈跟踪进行标识。

堆栈跟踪:

[FaultException`1: Store update, insert, or delete statement affected an unexpected number of rows (0). Entities may have been modified or deleted since entities were loaded. Refresh ObjectStateManager entries.] 
    System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg) +10259418 
    System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type) +539 
    myWebPortal.Repositories.UserServiceRef.IUserService.AddComputer(Int64 userId, Computer toAdd) +0 
    myWebPortal.Repositories.UserServiceRef.UseServiceClient.AddComputer(Int64 userId, Computer toAdd) in c:\users\katelyn\documents\my web project\myWebPortal.repositories\service references\userserviceref\reference.cs:1282 
    myWebPortal.Repositories.UserAccountRepository.AddComputer(Int64 userId, Computer computer) in C:\Users\katelyn\Documents\my Web Project\myWebPortal.Repositories\UserRepository.cs:238 
    myWebPortal.Web.Controllers.ComputerController.AddComputer(ComputerModel model) in C:\Users\katelyn\Documents\my Web Project\myWebPortal.Web\Controllers\ComputerController.cs:71 
    lambda_method(ExecutionScope , ControllerBase , Object[]) +69 
    System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters) +236 
    System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +31 
    System.Web.Mvc.<>c__DisplayClassd.<InvokeActionMethodWithFilters>b__a() +85 
    System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func`1 continuation) +632195 
    System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodWithFilters(ControllerContext controllerContext, IList`1 filters, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +288 
    System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName) +630660 
    System.Web.Mvc.Controller.ExecuteCore() +125 
    System.Web.Mvc.<>c__DisplayClass8.<BeginProcessRequest>b__4() +48 
    System.Web.Mvc.Async.<>c__DisplayClass1.<MakeVoidDelegate>b__0() +21 
    System.Web.Mvc.Async.<>c__DisplayClass8`1.<BeginSynchronous>b__7(IAsyncResult _) +15 
    System.Web.Mvc.Async.WrappedAsyncResult`1.End() +85 
    System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +51 
    System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +454 
    System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +263 

也尝试添加一台笔记本电脑/台式机,有时电脑行将被插入,但没有一台笔记本电脑/台式行时。

+0

你将永远不会*看到'OptimisticConcurrencyException',除非你有'ConcurrencyMode'是'Fixed'的一些字段。您不会显示,也不会显示编译的代码或生成的SQL。如果您需要帮助,您应该提供您正在使用的*真实代码和模型*,而不是您认为可能反映出您正在做什么的组成示例。 – 2010-03-01 18:32:53

+0

我没有在任何地方设置ConcurrencyMode。我认为它是OptimisticConcurrencyException,因为它被catch(OptimisticConcurrencyException e)块捕获。这是真正的代码。什么生成SQL?对不起,这里的新东西只是试图与linq-to-entities一起玩。 – user283802 2010-03-01 18:49:31

+0

不,一个'catch'块不能改变一个异常的类型,除非它抛出一个全新的异常(并且我假定你检查了这个异常)。如果您看到'OptimisticConcurrencyException',那么某处某个字段的'ConcurrencyMode'设置为'Fixed'。该功能的意图是通过例如SQL Server“TIMESTAMP”列进行乐观并发控制。要查看EF生成的SQL,请使用SQL Profiler。这将向你展示'UPDATE'语句,它应该阐明它为什么不实际更新任何数据。 – 2010-03-01 20:02:28

回答

1

你在哪里实例化/初始化entityToAdd

您能否确认外键约束和主键信息(自动增量,类型等)似乎由于某些原因,插入失败,被受影响的行数不正确所捕获。

尝试从SQL管理控制台中自己运行SQL - 你有什么错误吗?记录是否正确插入?

您可能还想确保桌子上没有可能导致问题的触发器或类似物。

+0

有类似的问题,同样的例外。我的问题是触发。 Tnx – 100r 2011-02-02 12:38:21

+0

@ 100r - 我也遇到这个错误。你是如何解决触发问题的。 – muruge 2011-06-17 23:26:18

+0

@muruge问题在于EF尝试跟踪对象状态并对其进行管理 - 触发器更改数据库中的状态,但不是EF缓存中的状态,从而导致错误匹配,从而可能在以后导致错误。最简单的方法是在DAL/BL中实现触发器,主要取决于它的原因 - 因此所有更改都是通过实体完成的。如果您想发布问题并提供问题的某些详细信息并给我们提供链接,我们会尽力为您提供其他方法。仅供参考可以扩展对象上下文以捕获可能对您有用的'SavingChanges'等事件。 – Basic 2011-06-18 13:33:46

1

我以前遇到同样的问题,它是由SQL Server中的INSTEAD OF触发器引起的。在我看来,当SQL Server报告查询成功完成时,发生OptimisticConcurrencyExceptions,但正在进行的SELECT语句不会返回预期的行数。

@mrunge在@ BasicLife的回答中提供了关于the solution I posted for that problem的评论。

另一个潜在的原因是用于插入和更新实体的存储过程。从http://msdn.microsoft.com/en-us/library/bb738618.aspx

可以在定义使用存储过程 进行更新,数据源的实体 数据模型 也出现一个OptimisticConcurrencyException。在 这种情况下,当使用 执行更新的存储过程报告更新了零个 行时,会引发异常 。

我相当确定在正常执行SQL查询期间发生的实际SQL错误(关键违规,空错误等)将使用与您看到的不同的异常来报告。我不记得例外的名称。