好久没更新EF这个系列了,现在又重新开始。

这次学习,开放式并发。首先拿出数据库脚本:

说明一下,这个数据库脚本是之前的章节中稍作修改的:

USE [SchoolDB]
GO

/****** Object:  Table [dbo].[Student]    Script Date: 11/30/2015 21:42:07 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE TABLE [dbo].[Student](
    [StudentID] [INT] NOT NULL,
    [StudentName] [NVARCHAR]() NULL,
    [StandardID] [INT] NULL,
    [RowVersion] [TIMESTAMP] NOT NULL,
 CONSTRAINT [PK__Student__32C52A7903317E3D] PRIMARY KEY CLUSTERED
(
    [StudentID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

GO

ALTER TABLE [dbo].[Student]  WITH CHECK ADD  CONSTRAINT [FK__Student__Standar__0519C6AF] FOREIGN KEY([StandardID])
REFERENCES [dbo].[Standard] ([StandardID])
GO

ALTER TABLE [dbo].[Student] CHECK CONSTRAINT [FK__Student__Standar__0519C6AF]
GO

然后,我们在数据模型中更新一下模型EDMx

可以看到Student模型上面,出现了Rowversion字段,我们选中它,右键-->属性,修改并发模式为Fixed。

EF will now include a RowVersion column in the where clause, whenever you do an update operation and if the rowversion value is different than in the where clause then it will throwDbUpdateConcurrencyExection.

下面开始实践:

using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.Core.Objects;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace EFTutorials
{
    class Program
    {
        static void Main(string[] args)
        {
            Student stu1 = null;
            Student stu2 = null;

            using (var db = new SchoolDBEntities1())
            {
                db.Configuration.ProxyCreationEnabled = false;

                stu1 = db.Students.Where(s => s.StudentID == ).FirstOrDefault();
            }

            using (var db = new SchoolDBEntities1())
            {
                db.Configuration.ProxyCreationEnabled = false;

                stu2 = db.Students.Where(s => s.StudentID == ).FirstOrDefault();
            }

            stu1.StudentName = "Edit Stuent1";
            stu2.StudentName = "Edit Stuent2";

            using (var db = new SchoolDBEntities1())
            {
                try
                {
                    db.Entry(stu1).State = EntityState.Modified;
                    db.SaveChanges();
                }
                catch (DbUpdateConcurrencyException ex)
                {
                    Console.WriteLine("Optimistic Concurrency exception occured");
                }

            }

            using (var db = new SchoolDBEntities1())
            {
                try
                {
                    db.Entry(stu2).State = EntityState.Modified;
                    db.SaveChanges();
                }
                catch (DbUpdateConcurrencyException ex)
                {
                    Console.WriteLine("Optimistic Concurrency exception occured");
                }

            }

        }
    }
}

执行完stu1那个查询之后:

SELECT TOP (1)
[Extent1].[StudentID] AS [StudentID],
[Extent1].[StudentName] AS [StudentName],
[Extent1].[StandardID] AS [StandardID],
[Extent1].[RowVersion] AS [RowVersion]
FROM [dbo].[Student] AS [Extent1]
WHERE 1 = [Extent1].[StudentID]

执行完,stu1的保存修改之后:

exec sp_executesql N'UPDATE [dbo].[Student]
SET [StudentName] = @0, [StandardID] = NULL
WHERE (([StudentID] = @1) AND ([RowVersion] = @2))
SELECT [RowVersion]
FROM [dbo].[Student]
WHERE @@ROWCOUNT > 0 AND [StudentID] = @1',N'@0 nvarchar(100),@1 int,@2 binary(8)',@0=N'Edit Stuent1',@1=1,@2=0x00000000000007D6

可以肯定的得出,在这里会出错,也就是并发。

Concurrency in Code-First:

You can create a timestamp property in code-first by usng [Timestamp] attribute. Make sure that the property type is byte[] because timestamp is binary in C#.

        [Timestamp]
        public byte[] RowVersion { get; set; }
        

EF includes a property in the where clause, during the update operation, if the property is marked with the Timestamp attribute.

You can resolve concurrency exceptions many ways. Visit msdn for detailed information on how to resolve optimistic concurrency.

Download sample project for the basic tutorials.

今天有点晚了,明天来继续,怎么解决这个并发。哈哈!!

EF中的开放式并发(EF基础系列--28)的更多相关文章

  1. Entity Framework入门教程(13)---EF中的高并发

    EF中的高并发 这里只介绍EF6中database-first开发方案的高并发解决方案,code-first开发方案中的高并发会在以后的EF CodeFirst系列中介绍. EF默认支持乐观并发:我们 ...

  2. ADO.NET 中的数据并发

    当多个用户试图同时修改数据时,需要建立控制机制来防止一个用户的修改对同时操作的其他用户所作的修改产生不利的影响.处理这种情况的系统叫做“并发控制”.并发控制的类型通常,管理数据库中的并发有三种常见的方 ...

  3. 6.翻译:EF基础系列---什么是EF中的实体?

    原文地址:http://www.entityframeworktutorial.net/basics/what-is-entity-in-entityframework.aspx EF中的实体就是继承 ...

  4. 10.翻译:EF基础系列---EF中的持久性

    原文链接:http://www.entityframeworktutorial.net/EntityFramework4.3/persistence-in-entity-framework.aspx ...

  5. 8.翻译:EF基础系列----EF中实体的状态

    原文链接:http://www.entityframeworktutorial.net/basics/entity-states.aspx 在实体的生命周期中,EF API维护着每一个实体的状态,对于 ...

  6. 7.翻译:EF基础系列---EF中的实体类型

    原文地址:http://www.entityframeworktutorial.net/Types-of-Entities.aspx 在Entity Framework中有两种实体类型:一种是POCO ...

  7. 5.翻译:EF基础系列---EF中的上下文类

    原文地址:http://www.entityframeworktutorial.net/basics/context-class-in-entity-framework.aspx EF中的上下文类是一 ...

  8. 1.翻译:EF基础系列--什么是Entity Framework?

    大家好,好久不见,EF系列之前落下了,还是打算重新整理一下. 先说说目前的打算:先简单了解一下EF基础系列-->然后就是EF 6 Code-First系列-->接着就是EF 6 DB-Fi ...

  9. 【Basics of Entity Framework】【EF基础系列1】

    EF自己包括看视频,看MSDN零零散散的学了一点皮毛,这次打算系统学习一下EF.我将会使用VS2012来学习这个EF基础系列. 现在看看EF的历史吧: EF版本 相关版本特性介绍 EF3.5 基于数据 ...

随机推荐

  1. Google云平台对于2014世界杯半决赛的预测,德国阿根廷胜!

    由于本人是个足球迷,前段日子Google利用自己云平台预测世界杯八进四的比赛并取得了75%的正确率的事情让我振动不小.虽然这些年一直听说大数据的预测和看趋势能力如何如何强大,但这次的感受更加震撼,因为 ...

  2. CSS 背景属性

    background: 简写属性,作用是将背景属性置在一个声明中 background-attachment: 背景图像是否固定或者随着页面的其余部队滚动 background-color: 设置元素 ...

  3. [实践] Android5.1.1源码 - 让某个APP以解释执行模式运行

    [实践] Android5.1.1源码 - 让某个APP以解释执行模式运行   作者:寻禹@阿里聚安全 前言 本文的实践修改了Android5.1.1的源码. 本文只简单的讲了一下原理.在“实践”一节 ...

  4. Logging with NLog

    相比较log4net, 我更喜欢NLog, 因为NLog 更简单, 而且配置选项也更加的清楚,可能是因为log4net 是从log4j 移植过来的一个原因吧,总感觉有很多的java 成分在. 要使用N ...

  5. [转]GC简介

    [转]GC简介 原文链接:http://www.cnblogs.com/cposture/p/4845189.html 原文写得太好了,这里转一下. 1 GC机制 1.1 对象 从计算机的角度,装有数 ...

  6. Visual Studio Code 调试 nodeJS

    Step 1: 点击Debug按钮,调出launch.json文件,更改program的路径为目标js文件. 生成的luanch.json文件在.vscode文件下 step2:接下来就可以加断点调试 ...

  7. spring快速入门(二)

    一.在spring快速入门(一)的基础上,我们来了解spring是如何解决对象的创建以及对象之间的依赖关系的问题 (比如client中依赖UserAction的具体实现,UserActionImpl中 ...

  8. xamarin UWP ActivityIndicator

    在xamarin的UWP平台使用ActivityIndicator时,如果你时后台创建的这个对象,请设置他的宽度,不然在UWP平台下会发现找不这个对象,其实是在这个平台和特点版本下的宽度没设置,导致有 ...

  9. 使用Emit把Datatable转换为对象集合(List<T>)

    Emit生成动态方法部分摘自网上,但是经过修改,加入了对委托的缓存以及类结构的调整,使之调用更简洁方便.大致的思路是:要实现转换datatable到某个指定对象的集合,本质是实现转换一个datarow ...

  10. 获取进程CPU占用率

    获取进程CPU占用率 // 时间转换 static __int64 file_time_2_utc(const FILETIME* ftime) { LARGE_INTEGER li; li.LowP ...