多个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());
}
}