多个DbContext修改同一张表测试
多个DbContext修改同一张表经测试是可行的。
UserStore和DepartmentStore都可以向SysLog表写入数据
用多个线程同时通过UserStore和DepartmentStore想SysLog表写入数据,数据能正确写入表中
实体代码:
public class Department
{
public String DeptId { get; set; }
public String DeptName { get; set; }
public String ParentId { get; set; } public DateTime? CreatedStamp { get; set; } public DateTime? UpdatedStamp { get; set; }
} public class SysLog
{
public SysLog() { Id = Guid.NewGuid().ToString(); }
/// <summary>
/// Id
/// </summary>
public String Id { get; set; }
/// <summary>
/// 参数
/// </summary>
public String Operator { get; set; }
/// <summary>
/// 信息
/// </summary>
public String Message { get; set; }
/// <summary>
/// 结果
/// </summary>
public String Result { get; set; }
/// <summary>
/// 类型
/// </summary>
public String Type { get; set; }
/// <summary>
/// 模组
/// </summary>
public String Module { get; set; }
/// <summary>
/// 创建时间
/// </summary>
public DateTime CreateTime { get; set; }
}
public class User
{
public String Uid { get; set; }
public String Passwrod { get; set; }
public String Name { get; set; }
public String QQ { get; set; }
public String Email { get; set; }
public String Tel { get; set; }
public String MobilePhone { get; set; }
public String DeptId { get; set; } public DateTime? CreatedStamp { get; set; } public DateTime? UpdatedStamp { get; set; }
}
数据库映射
public class DepartmentMapping: EntityTypeConfiguration<Department>
{
public DepartmentMapping()
{
ToTable("Department");
HasKey(t => t.DeptId);
Property(t => t.DeptId)
.HasColumnName("DeptId")
.HasColumnType("varchar")
.HasMaxLength(50); Property(t => t.DeptName)
.HasColumnName("DeptName"); Property(t => t.ParentId)
.HasColumnName("ParentId"); Property(t => t.CreatedStamp)
.HasColumnName("CreatedStamp"); Property(t => t.UpdatedStamp)
.HasColumnName("UpdatedStamp");
}
} public class SysLogMapping:EntityTypeConfiguration<SysLog>
{
public SysLogMapping()
{
ToTable("SysLog");
HasKey(t => t.Id); Property(t => t.Id)
.HasColumnName("Id")
.HasColumnType("varchar"); Property(t => t.CreateTime)
.HasColumnName("CreateTime");
Property(t => t.Message)
.HasColumnName("Message");
Property(t => t.Module)
.HasColumnName("Module");
Property(t=>t.Operator)
.HasColumnName("Operator");
Property(t => t.Result)
.HasColumnName("Result");
Property(t => t.Type)
.HasColumnName("Type");
}
} public class UsersMapping : EntityTypeConfiguration<User>
{
public UsersMapping()
{
this.ToTable("Users");
this.HasKey(t => t.Uid); /// <summary>
/// Uid
/// </summary>
this.Property(t => t.Uid)
.HasMaxLength(50)
.HasColumnName("Uid"); Property(t => t.Name)
.HasMaxLength(50)
.HasColumnName("Name"); Property(t => t.DeptId)
.HasMaxLength(50)
.HasColumnName("DeptId"); Property(t => t.Email)
.HasMaxLength(50)
.HasColumnName("Email"); Property(t => t.MobilePhone)
.HasMaxLength(50)
.HasColumnName("MobilePhone"); Property(t => t.Passwrod)
.HasMaxLength(50)
.HasColumnName("Passwrod"); Property(t => t.QQ)
.HasMaxLength(50)
.HasColumnName("QQ"); Property(t => t.Tel)
.HasMaxLength(50)
.HasColumnName("Tel"); Property(t => t.CreatedStamp)
.HasColumnName("CreatedStamp"); Property(t => t.UpdatedStamp)
.HasColumnName("UpdatedStamp");
}
}
数据库上下文
public class DepartmentStore : DbContext
{
public DepartmentStore(string nameOrConnectionString) : base(nameOrConnectionString) { } public DbSet<Department> Departments { get; set; }
public DbSet<SysLog> SysLog { get; set; } public void AddDepartment(Department department)
{
Departments.Add(department);
} public Department GetDepartment(String DeptId)
{
return Departments.FirstOrDefault(p => p.DeptId.Equals(DeptId));
} public Boolean RemoveDepartment(Department department)
{
return RemoveDepartment(department.DeptId);
} public Boolean RemoveDepartment(String DeptId)
{
var department = GetDepartment(DeptId);
if (department == null) return false;
Departments.Remove(department);
return true;
} public void AddLog(SysLog log)
{
SysLog.Add(log);
} protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Configurations.Add(new Mapping.DepartmentMapping());
modelBuilder.Configurations.Add(new Mapping.SysLogMapping());
}
}
public class UserStore:DbContext
{
public UserStore(string nameOrConnectionString) : base(nameOrConnectionString) { } public DbSet<User> Users { get; set; }
public DbSet<SysLog> SysLog { get; set; } public void AddUsers(User user)
{
Users.Add(user);
} public User GetUser(String Uid)
{
return Users.FirstOrDefault(p => p.Uid.Equals(Uid));
} public Boolean Remove(User user)
{
return Remove(user.Uid);
} public Boolean Remove(String Uid)
{
var user = GetUser(Uid);
if (user == null)
return false;
Users.Remove(user);
return true;
} public void AddLog(SysLog log)
{
SysLog.Add(log);
} protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Configurations.Add(new Mapping.UsersMapping());
modelBuilder.Configurations.Add(new Mapping.SysLogMapping());
}
}
业务操作
public class DepartmentService : IDisposable
{
DepartmentStore store = null; public DepartmentService(String nameOrConnectionString)
{
store = new DepartmentStore(nameOrConnectionString);
} public Boolean AddDepartement(Department dept)
{
//using (var store = new UserStore(_nameOrConnectionString))
//{
using (DbContextTransaction transaction = store.Database.BeginTransaction())
{
store.AddDepartment(dept);
store.AddLog(new SysLog
{
CreateTime = dept.CreatedStamp.Value,
Message = String.Format("添加部门【{0}】,名称【{1}】", dept.DeptId,dept.DeptName),
Module = "Department",
Result = "true",
Type = "Department"
});
Boolean result = store.SaveChanges() > 0;
store.SaveChanges();
transaction.Commit();
return result;
}
//}
}
public Boolean UpdateDepartment(Department newDept)
{
//using (var store = new UserStore(_nameOrConnectionString))
//{
var dept = store.GetDepartment(newDept.DeptId);
using (DbContextTransaction transaction = store.Database.BeginTransaction())
{
dept.DeptName = newDept.DeptName;
dept.ParentId = newDept.ParentId;
dept.UpdatedStamp = newDept.UpdatedStamp;
store.AddLog(new SysLog
{
CreateTime = newDept.UpdatedStamp.Value,
Message = String.Format("更新部门【{0}】,名称【{1}】", dept.DeptId, dept.DeptName),
Module = "Department",
Result = "true",
Type = "Department"
});
Boolean result = store.SaveChanges() > 0;
store.SaveChanges();
transaction.Commit();
return result;
}
//}
} public Boolean DeleteDepartment(String deptId)
{
using (DbContextTransaction transaction = store.Database.BeginTransaction())
{
if (store.RemoveDepartment(deptId))
{
store.AddLog(new SysLog
{
CreateTime = DateTime.Now,
Message = String.Format("删除部门【{0}】", deptId),
Module = "Department",
Result = "true",
Type = "String"
});
}
Boolean result = store.SaveChanges() > 0;
store.SaveChanges();
transaction.Commit();
return result;
}
} public void Dispose()
{
store.Dispose();
GC.ReRegisterForFinalize(this);
}
} String _nameOrConnectionString = String.Empty;
UserStore store = null;
public UserService(String nameOrConnectionString)
{
store = new UserStore(nameOrConnectionString);
_nameOrConnectionString = nameOrConnectionString;
} public Boolean AddUser(User user)
{
//using (var store = new UserStore(_nameOrConnectionString))
//{
using (DbContextTransaction transaction = store.Database.BeginTransaction())
{
store.AddUsers(user);
store.AddLog(new SysLog
{
CreateTime = user.CreatedStamp.Value,
Message = String.Format("添加用户【{0}】名称【{1}】", user.Uid, user.Name),
Module = "User",
Result = "true",
Type = "User"
});
Boolean result = store.SaveChanges() > 0;
store.SaveChanges();
transaction.Commit();
return result;
}
//}
} public Boolean UpdateUser(User newUser)
{
//using (var store = new UserStore(_nameOrConnectionString))
//{
var user = store.GetUser(newUser.Uid);
using (DbContextTransaction transaction = store.Database.BeginTransaction())
{
user.Name = newUser.Name;
user.MobilePhone = newUser.MobilePhone;
user.Passwrod = newUser.Passwrod;
user.QQ = newUser.QQ;
user.Tel = newUser.Tel;
user.UpdatedStamp = newUser.UpdatedStamp;
store.AddLog(new SysLog
{
CreateTime = newUser.UpdatedStamp.Value,
Message = String.Format("更新用户【{0}】名称【{1}】", user.Uid, user.Name),
Module = "User",
Result = "true",
Type = "User"
});
Boolean result = store.SaveChanges() > 0;
store.SaveChanges();
transaction.Commit();
return result;
}
//}
} public Boolean DeleteUser(String uid)
{
using (DbContextTransaction transaction = store.Database.BeginTransaction())
{
if (store.Remove(uid))
{
store.AddLog(new SysLog
{
CreateTime = DateTime.Now,
Message = String.Format("删除用户【{0}】", uid),
Module = "User",
Result = "true",
Type = "String"
});
}
Boolean result = store.SaveChanges() > 0;
store.SaveChanges();
transaction.Commit();
return result;
}
} public void Dispose()
{
store.Dispose();
GC.ReRegisterForFinalize(this);
}
}
测试
public class TestEntityFramework
{
const String connectionString = "data source=.;initial catalog=DataBaseName;user id=UID;password=Pwd;";
public TestEntityFramework()
{
var task1 = Task.Factory.StartNew(() =>
{
UserService userService = new UserService(connectionString);
userService.DeleteUser("TestUser1");
userService.AddUser(new EntityFramework.Model.User
{
Uid = "TestUser1",
DeptId = "Detpid1",
Email = "Email@Test.com",
MobilePhone = "13429870975",
Name = "TestUserName1",
Passwrod = "21332432",
QQ = "36592369562",
Tel = "0755-75935275",
CreatedStamp = DateTime.Now
});
userService.Dispose();
});
var task2 = Task.Factory.StartNew(() =>
{
DepartmentService service = new DepartmentService(connectionString);
service.DeleteDepartment("Detpid1");
service.AddDepartement(new EntityFramework.Model.Department
{
DeptId = "Detpid1",
DeptName = "DeptName1",
ParentId = String.Empty,
CreatedStamp = DateTime.Now
});
service.Dispose();
});
Task.WaitAll(task1, task2);
} public void Test()
{
List<Task> list = new List<Task>();
int i = 1;
do
{
var task = Task.Factory.StartNew((index) =>
{
UserService userService = new UserService(connectionString);
userService.UpdateUser(new EntityFramework.Model.User
{
Uid = "TestUser1",
DeptId = "Detpid1" + index.ToString(),
Email = "Email@Test.com" + index.ToString(),
MobilePhone = "13429870975" + index.ToString(),
Name = "TestUserName1" + index.ToString(),
Passwrod = "21332432" + index.ToString(),
QQ = "36592369562" + index.ToString(),
Tel = "0755-75935275" + index.ToString(),
UpdatedStamp = DateTime.Now
});
userService.Dispose();
}, i);
list.Add(task);
} while (i++ < 10); i = 1;
do
{
var task = Task.Factory.StartNew((index) =>
{
DepartmentService service = new DepartmentService(connectionString);
service.UpdateDepartment(new EntityFramework.Model.Department
{
DeptId = "Detpid1",
DeptName = "DeptName1" + index.ToString(),
ParentId = String.Empty,
UpdatedStamp = DateTime.Now
});
service.Dispose();
}, i);
list.Add(task);
} while (i++ < 10); Task.WaitAll(list.ToArray());
}
}
多个DbContext修改同一张表测试的更多相关文章
- 修改2张表不同SESSION相互持有记录引发的死锁
死锁产生的原因:如果有两个会话,每个会话都持有另一个会话想要的资源,此时就会发生死锁. 2张表不同SESSION持有不同记录 SQL> create table t1(id int); Tabl ...
- 利用pymysql同时修改两张表的数据
使用pymysql操作数据库中相关联的两张表需求:两张表中分别有一个字段是json格式,需要往json中再插入一个属性值’container_cloud’=’fasle’. import pymysq ...
- 关于如何修改一张表中所有行与选定字段的同sql多行语句的添加方法
利用Excel以及word文档进行操作 将表的字段以及数据全部放入Excel表中并保存. 在word表中将写好的sql语句放入文档,利用邮件--选择收件人--使用现有列表--(选择之前做好的Excel ...
- 不同数据库中同一张表的SQL循环修改语句
select sample_value,Sample_GUID,row_number() over(order by sample_value )as rownumber into #AATemp ...
- MySQL将一张表的某些列数据,复制到另外一张表,并且修改某些内容
MySQL将一张表的某些列数据,复制到另外一张表 INSERT INTO t_topic_content(content,topicId) SELECT content,id FROM t_topi ...
- Django学习——图书管理系统图书修改、orm常用和非常用字段(了解)、 orm字段参数(了解)、字段关系(了解)、手动创建第三张表、Meta元信息、原生SQL、Django与ajax(入门)
1 图书管理系统图书修改 1.1 views 修改图书获取id的两种方案 1 <input type="hidden" name="id" value=& ...
- oracle创建第三方数据接口表,指定特定用户访问某张表
/*****创建用户并指定操作哪张表开始******/ --1.创建用户并设置默认表空间 CREATE USER CHENGDWY IDENTIFIED BY CHENGDWY DEFAULT TAB ...
- EF Core中如何正确地设置两张表之间的关联关系
数据库 假设现在我们在SQL Server数据库中有下面两张表: Person表,代表的是一个人: CREATE TABLE [dbo].[Person]( ,) NOT NULL, ) NULL, ...
- mycat读写分离+垂直切分+水平切分+er分片+全局表 测试
原文http://blog.163.com/bigoceanwu@126/blog/static/172718064201683031639683/ 读写分离:利用最基础的mysql主从复制,事务性的 ...
随机推荐
- AndFix使用感想
AndFix已经使用了一段时间了,但是到AndFix上看了一下,最近2个月都没有更新代码了,有141个issues和3个pull request没人处理,其实AndFix的Contributors就俩 ...
- 使用swift语言进行IOS应用开发
在Swift中能够直接使用Objective-C语言提供的api (包括系统框架与自己的定制代码),也能够在Objective-C中使用Swift提供的类和api ,还能够在一个工程中同时混合使用Sw ...
- 不用局部变量实现C语言两数交换算法
关于交换算法,我想非常简单,所以,这次不做分析,直接上代码: #include <stdio.h> #include <stdlib.h> //用异或方式实现 void swa ...
- python JoinableQueue在生产者消费者项目中的简单应用
class multiprocessing.JoinableQueue([maxsize]) JoinableQueue, a Queue subclass, is a queue which add ...
- Java工程师成神之路思维导图
前面看Hollis的微信公众号更新了Java工程师成神之路的文档,感觉里面的内容清晰.齐全,可以用来审视自己,也能够知道自己在那些方面可以继续前行,想着有时间把它画下来,画下来之后分享出来. 主要内容 ...
- 关于web页面JApplet打印小票
版权所有 做这个的例子太少,我把我做的示例亮出来 一.先说说需要的版本 1.我用的浏览器只有ie: 火狐只支持52版本以下,并且是java7.java8.chrome不支持 2.applet客户端打印 ...
- Numpy快速入门——shape属性,你秒懂了吗
前言 对于学习NumPy(Numeric Python),首先得明确一点是:Numpy 是用来处理矩阵数组的. shape 属性 对于shape函数,官方文档是这么说明: the dimensions ...
- Eclipse安装SVN插件(转载)
http://www.cnblogs.com/ruiati/p/3584120.html 1.下载最新的Eclipse,我的版本是3.7.2 indigo(Eclipse IDE for Java E ...
- MySql 时间操作(今天,昨天,7天,30天,本月,上月)
1 . 查看当天日期 select current_date(); 2. 查看当天时间 select current_time(); 3.查看当天时间日期 select current_timesta ...
- 2017 Gartner数据科学魔力象限出炉,16位上榜公司花落谁家?
https://www.leiphone.com/news/201703/iZGuGfnER4Sv2zRe.html 2017年Gartner数据科学平台(在2016年被称作“高级分析平台”)的魔力象 ...