实体框架 - 乐观并发问题 [英] Entity Framework - Optimistic Concurrency Issue

查看:139
本文介绍了实体框架 - 乐观并发问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Windows服务,每10秒运行一次...每次运行,它需要一些测试数据,修改它,并使用EntityFramework持久化它到数据库。但是,在每次第二次运行时,当我尝试持久化更改时,我得到以下乐观并发异常: -

I have a windows service that runs every 10 seconds ... each time it runs, it takes some test data, modifies it and persists it to the database using the EntityFramework. However, on every second run, when I try to persist the change I get the following Optimistic Concurrency Exception:-


或delete语句影响了意外的行数(0)。实体可能已被修改或删除,因为实体已加载。刷新ObjectStateManager条目

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

我知道一个事实,即没有什么别的写入到该数据库,但我的服务每10秒更新记录。在这里可能会导致并发异常?

I know for a fact that there is nothing else writing to that DB but my service which updates records every 10 seconds. What could be causing the concurrency exception here ?

我认为对象图中某处的相关实体在第二次保存操作之前被修改。
所有我做的确实是实例化一个新的对象上下文,并调用保存操作上一些记录,我使用相同的上下文检索。
以下代码工作---

I think a related entity somewhere in the object graph was getting modified prior to the second save operation. All i am doing really is instantiating a new object context, and calling a save operation on some records i had retrieved using the same context. The following code worked ---

var ctx = new blahEntities();
var profile = ctx.ProfileSet.Where(pr=>pr.FirstName.Contains("a")).FirstOrDefault();
profile.Address = "modified";
ctx.SaveChanges();
ctx.Refresh(RefreshMode.StoreWins,profile);


推荐答案

意外的行数很可能你没有在你的实体模型中正确映射或定义一个ID字段,或者你正在修改一个分离的实体并尝试保存它,它没有关键信息。

The "unexpected number of rows (0)" indicates that more than likely you don't have an ID field correctly mapped or defined in your entity model, or you are modifying a detached entity and attempting to save it and it doesn't have key information.

运行SQL Server分析器或Entity Framework Profiler,并查看后台进行的操作。

Run SQL Server profiler, or Entity Framework Profiler, and see what is going on in the background.

这篇关于实体框架 - 乐观并发问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆