2012-08-16 215 views
1

我无法更新当我更改我的表中的某个字段。实体框架更新

  • 数据库==> mysql的
  • .NET框架==> 4.0
  • 平台==> WPF应用程序

让我一步一步讲解

我的目标是更新表中已经存在的项目。

public bool SaveToVideoInfo(List<tblvideoinfo> vList,sbyte profilID) 
    { 
        foreach (tblvideoinfo _videoinfo in vList) 
      { 

       try 
       { 

       ent.AddTotblvideoinfo(_videoinfo); 
       ent.AddTotblprocess(CreateProcess(profilID,_videoinfo.VideoID)); 
       ent.SaveChanges(); 

       } 
       catch (UpdateException) 
       { 

        return UpdateToVideoInfo(_videoinfo); 
       }    
     } 

      return false;      
    } 

如果在表中存在已经项,我赶上这个例外,并打电话给我更新功能

public bool UpdateToVideoInfo(tblvideoinfo vInfo) 
    { 

     var updatingItem = (from a in ent.tblvideoinfo 
        where a.VideoID == vInfo.VideoID 
        select a).First(); 

     updatingItem.SearchKeywords = vInfo.SearchKeywords; 
     updatingItem.SearchTimeStamp = DateTime.Now; 

     return ent.SaveChanges() > 0; 

    } 

因为如果在表中存在,我想改变一些领域如我上面写的。一切都很好,直到运行ent.SaveChanges()

我检查updatingItem已经改变了我设置的属性(SearchKeywords,SearchTimeStamp)

但出现此错误,同时更新条目中出现

错误。详情请参阅

内部异常下面是详细介绍

at System.Data.Mapping.Update.Internal.UpdateTranslator.Update(IEntityStateManager stateManager, IEntityAdapter adapter) 
    at System.Data.EntityClient.EntityAdapter.Update(IEntityStateManager entityCache) 
    at System.Data.Objects.ObjectContext.SaveChanges(SaveOptions options) 
    at System.Data.Objects.ObjectContext.SaveChanges() 
    at MyDbHelper.DBHelper.UpdateToVideoInfo(tblvideoinfo vInfo) 
    at MyDbHelper.DBHelper.SaveToVideoInfo(List`1 vList, SByte profilID) 
    at youtube.MainWindow.p_Drop_Event(Object sender, Object to) in C:\Users\xxxxxx....\...\MainWindow.xaml.cs:line 1125 
    at youtube.product.UserControl_MouseUp(Object sender, MouseButtonEventArgs e) in C:\Users\xxxxxx....\...\product.xaml.cs:line 239 
    at System.Windows.Input.MouseButtonEventArgs.InvokeEventHandler(Delegate genericHandler, Object genericTarget) 
    at System.Windows.RoutedEventArgs.InvokeHandler(Delegate handler, Object target) 
    at System.Windows.RoutedEventHandlerInfo.InvokeHandler(Object target, RoutedEventArgs routedEventArgs) 
    at System.Windows.EventRoute.InvokeHandlersImpl(Object source, RoutedEventArgs args, Boolean reRaised) 
    at System.Windows.UIElement.RaiseEventImpl(DependencyObject sender, RoutedEventArgs args) 
    at System.Windows.UIElement.RaiseTrustedEvent(RoutedEventArgs args) 
    at System.Windows.UIElement.RaiseEvent(RoutedEventArgs args, Boolean trusted) 
    at System.Windows.Input.InputManager.ProcessStagingArea() 
    at System.Windows.Input.InputManager.ProcessInput(InputEventArgs input) 
    at System.Windows.Input.InputProviderSite.ReportInput(InputReport inputReport) 
    at System.Windows.Interop.HwndMouseInputProvider.ReportInput(IntPtr hwnd, InputMode mode, Int32 timestamp, RawMouseActions actions, Int32 x, Int32 y, Int32 wheel) 
    at System.Windows.Interop.HwndMouseInputProvider.FilterMessage(IntPtr hwnd, WindowMessage msg, IntPtr wParam, IntPtr lParam, Boolean& handled) 
    at System.Windows.Interop.HwndSource.InputFilterMessage(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled) 
    at MS.Win32.HwndWrapper.WndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled) 
    at MS.Win32.HwndSubclass.DispatcherCallbackOperation(Object o) 
    at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs) 
    at MS.Internal.Threading.ExceptionFilterHelper.TryCatchWhen(Object source, Delegate method, Object args, Int32 numArgs, Delegate catchHandler) 
    at System.Windows.Threading.Dispatcher.LegacyInvokeImpl(DispatcherPriority priority, TimeSpan timeout, Delegate method, Object args, Int32 numArgs) 
    at MS.Win32.HwndSubclass.SubclassWndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam) 
    at MS.Win32.UnsafeNativeMethods.DispatchMessage(MSG& msg) 
    at System.Windows.Threading.Dispatcher.PushFrameImpl(DispatcherFrame frame) 
    at System.Windows.Threading.Dispatcher.PushFrame(DispatcherFrame frame) 
    at System.Windows.Threading.Dispatcher.Run() 
    at System.Windows.Application.RunDispatcher(Object ignore) 
    at System.Windows.Application.RunInternal(Window window) 
    at System.Windows.Application.Run(Window window) 
    at System.Windows.Application.Run() 
    at youtube.App.Main() in C:\Users\xxxxxx....\...\Debug\App.g.cs:line 0 
    at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args) 
    at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args) 
    at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly() 
    at System.Threading.ThreadHelper.ThreadStart_Context(Object state) 
    at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx) 
    at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx) 
    at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state) 
    at System.Threading.ThreadHelper.ThreadStart() 

这里updatingItem

的详细

here is detail of updatingItem

手段,

updatingItem.SearchKeywords = vInfo.SearchKeywords; 
    updatingItem.SearchTimeStamp = DateTime.Now; 

这些代码是工作。

与此同时,VideoID是唯一在我的表然后我不能添加具有相同VideoID的项目。但我想更新它。我认为更新问题来自这里。

我不想使用sql命令。

我只是想更新表的两个领域...

+0

什么是内部异常的描述? – 2012-08-16 13:10:11

+0

我已经在那里写下“这里是详细信息” – unbalanced 2012-08-16 13:11:06

+1

这是堆栈跟踪不是说明 – 2012-08-16 13:17:22

回答

1

我的猜测是,当您在同一个上下文中再次调用SaveChanges时,它试图插入重复插入操作并再次失败。

在catch块的开头调用ent.AcceptAllChanges()可能会起作用。

也许处置上下文并创建另一个用于更新函数将是最简单的选择。否则,您将需要将ObjectStateEntry.State更改为Unchanged您尝试插入的两个实体(videoinfo,进程)。

+0

thanx。 ent.AcceptAllChanges();它使删除错误。但在这个时候,savechanges方法返回0,并在表中,没有任何变化.. – unbalanced 2012-08-16 13:18:39

+0

你是否尝试将该调用放置在catch块的开始? – Omtara 2012-08-16 13:20:01

+0

不,我没有:)但它的作品。你是伟大的:)非常感谢你:)我写了它开始的catch块和工作:) – unbalanced 2012-08-16 13:22:21

0

有没有办法来检查,如果该项目是新的?您可以将id设置为0值或其他值,以便您可以轻松查看该项目是否为新项目。

如果这是不可能的,你可以在Id上使用SingleOrDefault来检查实体是否存在。这样你就可以避免updatexception并在一次调用中处理所有事情。根据这种情况下的数据库例外情况,这不是一个很干净的解决方案

在一次调用中处理所有事情应该可以解决您的问题。

+0

我看到,但问题是我该如何更新这个项目?这是不可能的 ?在sql中,我会写“update tblvideoinfo set SearchKeywords ='bla bla'and SearchTimeStamp ='bla bla'where videoID ='blabla ...'” – unbalanced 2012-08-16 13:13:37

+0

加载一个项目并在ObjectContext范围内修改它自动跟踪更改。调用SaveChanges将生成更新Sql – 2012-08-16 13:19:16

+0

感谢您的关注。 @Omtara已经解决了这个问题。 – unbalanced 2012-08-16 13:28:00

1

尝试调用

var updatingItem = (from a in ent.tblvideoinfo 
        where a.VideoID == vInfo.VideoID 
        select a).FirstOrDefault(); 

和你正在使用

updatingItem.SearchTimeStamp = DateTime.Now; 

使用该字段的数据类型相同(日期时间),你的数据库不?

一个选项是处理ObjectContext.SavingChanges事件,它使您有机会在保存更改之前对实体执行验证,甚至在必要时取消保存。通过这种方式,您可以确保在尝试保存更改之前设置了任何不可为空的属性,并避免必须依赖异常处理。

+0

我已经可以保存项目。但如果项目表中有相同的videoid我不能更新它。但@Omtara解决了这个问题 – unbalanced 2012-08-16 13:23:45

+0

好的:).......... – 2012-08-16 13:24:54

+0

thanx的注意。我没有updateitem的任何问题,因为我提到这是很好的。但它没关系,它不工作,没有问题:)谢谢 – unbalanced 2012-08-16 13:26:04