private void btnStateTest_Click(object sender, EventArgs e) { var shop = new Shop(); shop.ShId = Guid.NewGuid(); shop.ShCode = txtCode.Text; shop.ShName = txtName.Text; shop.ShDomainId = Guid.Empty; shop.ShIdentityCode = DateTime.Now.ToString("yyyyMMddHHmmss"); var state = shop.State; Shop modelInContext = null; using (var scope = DbScope.Create()) { var context = scope.DbContexts.Get <FreeDbContext>(); modelInContext = DbScope.Parse <Shop>(context, shop); state = modelInContext.State; scope.SaveChanges(); } state = modelInContext.State; }
public void DeleteCategories(DeleteCategoriesParameter param) { using (var scope = DbScope.Create()) using (var context = base.CreateContext()) { scope.BeginTransaction(); var q = context.NewsCategories.Where(t => param.RowIDSet.Contains(t.RowID)); foreach (var item in q) { if (context.News.Any(t => t.CategoryID == item.RowID)) { throw new InvalidInvokeException("不能删除有新闻的分类"); } //更新子类的父类为被删除类别的父类。 context.NewsCategories.Update(t => t.ParentID == item.RowID, t => new NewsCategory { ParentID = item.ParentID }); } q.Delete(); scope.Complete(); } CacheInterceptorAttribute.ClearCache(_QueryCategories); }
public List <IShop> GetList() { using (var scope = DbScope.Create()) { return(scope.DbContexts.Get <FreeDbContext>().Shop.Where(n => n.ShDomainId == domainId).ToList().Cast <IShop>().ToList()); } }
public void ChangePassword(ChangePasswordParameter param) { using (var context = base.CreateUserContext()) { EmailAuth emailAuth = null; MobileAuth mobileAuth = null; if (param.AuthCode != null) { Guid emailAuthCode; if (Guid.TryParse(param.AuthCode, out emailAuthCode)) { emailAuth = this.CheckUserEmailAuth(context, emailAuthCode); } else { string[] mobileAuthCode = param.AuthCode.Split(','); if (mobileAuthCode.Length != 2) { throw new InvalidInvokeException("参数错误"); } mobileAuth = this.CheckUserMobileAuth(context, mobileAuthCode[0], int.Parse(mobileAuthCode[1])); param.UserName = mobileAuth.UserName; } } var id = this.SignIn(new SignInParameter() { AppID = param.AppID, UserName = param.UserName, Password = param.OldPassword }); if (!id.IsAuthenticated) { throw new InvalidInvokeException("账户不存在或密码错误"); } using (var scope = DbScope.Create()) { scope.BeginTransaction(); param.NewPassword = CryptoManaged.MD5Hex(param.NewPassword); context.Accounts.Update(t => t.RowID == id.UserID, t => new Account() { Password = param.NewPassword }); if (emailAuth != null) { emailAuth.Status = (int)ActivationStatus.Activated; } if (mobileAuth != null) { mobileAuth.Status = (int)ActivationStatus.Activated; } context.SaveChanges(); scope.Complete(); } } }
private void button1_Click(object sender, EventArgs e) { using (var scope = DbScope.Create()) { var list = scope.DbContexts.Get <FreeDbContext>().Shop.ToList(); txtName.Text = list.Count.ToString(); } }
/// <summary> /// 测试EF对Suppress事务的效果, OK /// 注意:除了用Suppress事务选项,还必须用DbContextScopeOption.ForceCreateNew 创建Scope /// </summary> private void TransactionTest2() { var shop = new Shop(); shop.ShId = Guid.NewGuid(); Shop modelInContext = null; using (var trans = new TransactionScope()) { using (var scope = DbScope.Create()) { var context = scope.DbContexts.Get <FreeDbContext>(); modelInContext = DbScope.Parse(context, shop); //modelInContext = context.Shop.Add(shop); modelInContext.ShCode = txtCode.Text; modelInContext.ShName = txtName.Text; modelInContext.ShDomainId = Guid.Empty; modelInContext.ShIdentityCode = DateTime.Now.ToLongTimeString(); using (var trans2 = new TransactionScope(TransactionScopeOption.Suppress)) { using (var scope2 = DbScope.Create(DbContextScopeOption.ForceCreateNew)) { shop = new Shop(); shop.ShId = Guid.NewGuid(); context = scope2.DbContexts.Get <FreeDbContext>(); modelInContext = DbScope.Parse(context, shop); //modelInContext = context.Shop.Add(shop); modelInContext.ShCode = txtCode.Text; modelInContext.ShName = txtName.Text; modelInContext.ShDomainId = Guid.Empty; modelInContext.ShIdentityCode = DateTime.Now.ToString("yyyyMMddHHmmssfff"); scope2.SaveChanges(); } trans2.Complete(); } scope.SaveChanges(); } //trans.Complete(); } }
/// <summary> /// 注册 /// </summary> /// <param name="param"></param> public void SignUp(SignUpParameter param) { string orgPwd = param.Password; param.Password = CryptoManaged.MD5Hex(param.Password); using (var scope = DbScope.Create()) using (var context = base.CreateUserContext()) { scope.BeginTransaction(); if (this.IsUserNameExists(new IsUserNameExistsParameter() { AppID = param.AppID, UserName = param.UserName })) { throw new InvalidInvokeException(SignUpErrorCode.AccountExist.ToDescription()); } var dataObj = new Account(); EntityMapper.Map <SignUpParameter, Account>(param, dataObj); dataObj.RowID = Guid.NewGuid(); dataObj.CreateDate = DateTime.Now; context.Accounts.Add(dataObj); context.SaveChanges(); if (param.SmsCode != default(int)) { VerifyMobile(new VerifyMobileParameter() { Mobile = param.Mobile, SmsCode = param.SmsCode }); } scope.Complete(); if (!string.IsNullOrEmpty(param.Email)) { this.SendAuthEmail(new SendAuthEmailParameter() { AppID = param.AppID, UserID = dataObj.RowID, Email = param.Email, Kind = AuthEmailKind.SignUp }); } } }
/// <summary> /// 测试EF 和 普通ado.net同时在一个事务中 /// 在修改了OracleAcessDataBase中的代码,对连接进行及时关闭后,已实现事务中EF和EntLib共存。但必须保证2种方式的连接字符串一样。 /// /// </summary> private void TransactionTest3() { var shop = new Shop(); shop.ShId = Guid.NewGuid(); using (var trans = new TransactionScope()) { using (var scope = DbScope.Create()) { var context = scope.DbContexts.Get <FreeDbContext>(); shop.ShCode = txtCode.Text; shop.ShName = txtName.Text; shop.ShDomainId = Guid.Empty; string sql = "select getidentitycode() from dual"; var connStr = "DATA SOURCE=//192.168.0.11/YUNSH;PASSWORD=jooge2012;PERSIST SECURITY INFO=True;USER ID=TERRY_1116;PROMOTABLE TRANSACTION=LOCAL;"; OracleCommand cmd; using (var conn = new OracleConnection(connStr)) { cmd = new OracleCommand(sql, conn); if (conn.State == ConnectionState.Closed) { conn.Open(); } var obj = cmd.ExecuteScalar(); shop.ShIdentityCode = obj.ToString(); } sql = string.Format("insert into t1 values('{0}')", DateTime.Now); OracleHelper.ExecuteNonQuery(connStr, sql); DbScope.Parse(context, shop); scope.SaveChanges(); } trans.Complete(); } }
/// <summary> /// 验证手机 /// </summary> /// <param name="smsCode"></param> /// <returns></returns> public void VerifyMobile(VerifyMobileParameter param) { using (var scope = DbScope.Create()) using (var context = base.CreateUserContext()) { scope.BeginTransaction(); var entity = this.CheckUserMobileAuth(context, param.Mobile, param.SmsCode); entity.Status = (int)ActivationStatus.Activated; context.SaveChanges(); context.Accounts.Update(t => t.UserName == entity.UserName, t => new Account() { Mobile = entity.Mobile, Flags = t.Flags | (int)UserFlags.AuthenticMobile }); scope.Complete(); } }
/// <summary> /// 通过传递的验证数值 验证邮箱的真实性 /// </summary> /// <param name="authCode"></param> public void VerifyEmail(Guid authCode) { using (var scope = DbScope.Create()) using (var context = base.CreateUserContext()) { scope.BeginTransaction(); var entity = CheckUserEmailAuth(context, authCode); entity.Status = (int)ActivationStatus.Activated; context.SaveChanges(); context.Accounts.Update(t => t.RowID == entity.UserID, t => new Account() { Email = entity.Email, Flags = t.Flags | (int)UserFlags.AuthenticEmail }); scope.Complete(); } }
public void Save(IShop shop) { using (var scope = DbScope.Create()) { var context = scope.DbContexts.Get <FreeDbContext>(); if (shop.ShId == null) { shop.ShId = Guid.NewGuid(); } var model = DbScope.Parse(context, shop as Shop); model.ShDomainId = domainId; model.ShIdentityCode = DateTime.Now.ToString("yyyyMMddHHmmss"); scope.SaveChanges(); } }
/// <summary> /// 无事务 /// </summary> private void NoTransactionSpeedTest() { StringBuilder sb = new StringBuilder(); var code = DateTime.Now.ToString("yyyyMMddHHmmssfff"); var connStr = "DATA SOURCE=//192.168.0.11/YUNSH;PASSWORD=jooge2012;PERSIST SECURITY INFO=True;USER ID=TERRY_1116;PROMOTABLE TRANSACTION=LOCAL;"; var watch = new Stopwatch(); watch.Start(); //没有事务 //先用ef插入店铺表n次 var times = 1200; using (var scope = DbScope.Create()) { for (var i = 0; i < times; i++) { var identityCode = code + i; var shop = new Shop(); shop.ShId = Guid.NewGuid(); var context = scope.DbContexts.Get <FreeDbContext>(); shop.ShCode = txtCode.Text; shop.ShName = txtName.Text; shop.ShDomainId = Guid.Empty; shop.ShIdentityCode = identityCode; //context.Shop.Add(shop); DbScope.Parse(context, shop); } scope.SaveChanges(); } watch.Stop(); sb.AppendFormat("EF无事务插入 {0} 次:{1} 毫秒 \r\n", times, watch.ElapsedMilliseconds); watch.Restart(); code = DateTime.Now.ToString("yyyyMMddHHmmssfff"); //再用EntLib插入 for (var i = 0; i < times; i++) { var identityCode = code + i; string sql = "insert into \"SHOP\"(\"SHID\", \"SHDOMAINID\", \"SHIDENTITYCODE\", \"SHCODE\", \"SHNAME\", \"SHDEFAULTWAREHOUSE\", \"SHWEBSHOPPLATFORMTYPE\", \"SHSHORTCUTCODE\", \"SHOUTERCODE\", \"SHWEBSHOPTYPE\", \"SHDESC\", \"SHTYPE\", \"SHLEVEL\", \"SHISWEBSHOP\", \"SHWEBSHOPID\", \"SHWEBSHOPURL\", \"SHWEBSHOPUSERIDENTITY\", \"SHWEBSHOPAPPKEY\", \"SHWEBSHOPAPPSECRET\", \"SHWEBSHOPSESSIONKEY\", \"SHWEBSHOPSESSIONTAG\", \"SHENABLED\", \"SHOWNERNICK\", \"SHOWNERNAME\", \"SHCOUNTRY\", \"SHPROVINCE\", \"SHCITY\", \"SHDISTRICT\", \"SHADDRESS\", \"SHPOSTCODE\", \"SHPHONE\", \"SHFAX\", \"SHAREA\", \"SHTEXT1\", \"SHTEXT2\", \"SHTEXT3\", \"SHTEXT4\", \"SHTEXT5\", \"SHTEXT6\", \"SHTEXT7\", \"SHTEXT8\", \"SHTEXT9\", \"SHTEXT10\", \"SHLONGTEXT1\", \"SHLONGTEXT2\", \"SHLONGTEXT3\", \"SHCHECKBOX1\", \"SHCHECKBOX2\", \"SHCHECKBOX3\", \"SHCHECKBOX4\", \"SHCHECKBOX5\", \"SHDATE1\", \"SHDATE2\", \"SHDATE3\", \"SHINT1\", \"SHINT2\", \"SHINT3\", \"SHDECIMAL1\", \"SHDECIMAL2\", \"SHDECIMAL3\", \"SHCREATEUSER\", \"SHCREATETIME\", \"SHLASTUPDATEUSER\", \"SHLASTUPDATETIME\", \"SHINVEXPSETTING\", \"SHWEBSHOPOTHERPARAM\", \"SHRELATECUSTOMER\") values (:p0, :p1, :p2, :p3, :p4, null, null, null, null, null, null, null, null, :p5, null, null, null, null, null, null, null, :p6, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, :p7, :p8, :p9, :p10, :p11, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null)"; List <OracleParameter> list = new List <OracleParameter> { new OracleParameter("p0", OracleDbType.Raw, Guid.NewGuid().ToByteArray(), ParameterDirection.Input), new OracleParameter("p1", OracleDbType.Raw, Guid.Empty.ToByteArray(), ParameterDirection.Input), new OracleParameter("p2", OracleDbType.NVarchar2, identityCode, ParameterDirection.Input), new OracleParameter("p3", OracleDbType.NVarchar2, txtName.Text, ParameterDirection.Input), new OracleParameter("p4", OracleDbType.NVarchar2, txtCode.Text, ParameterDirection.Input), new OracleParameter("p5", OracleDbType.Int16, 0, ParameterDirection.Input), new OracleParameter("p6", OracleDbType.Int16, 0, ParameterDirection.Input), new OracleParameter("p7", OracleDbType.Int16, 0, ParameterDirection.Input), new OracleParameter("p8", OracleDbType.Int16, 0, ParameterDirection.Input), new OracleParameter("p9", OracleDbType.Int16, 0, ParameterDirection.Input), new OracleParameter("p10", OracleDbType.Int16, 0, ParameterDirection.Input), new OracleParameter("p11", OracleDbType.Int16, 0, ParameterDirection.Input), }; OracleHelper.ExecuteNonQuery(connStr, sql, list.ToArray()); } watch.Stop(); sb.AppendFormat("EntLib无事务插入 {0} 次:{1} 毫秒 \r\n", times, watch.ElapsedMilliseconds); MessageBox.Show(sb.ToString()); }
/// <summary> /// Suppress 事务需要另外创建connection才有效,否则会一起回滚 /// 而且此时不会有DTC问题,应该是因为不在一个事务中。 /// </summary> private void TransactionTest1() { var shop = new Shop(); shop.ShId = Guid.NewGuid(); Shop modelInContext = null; using (var trans = new TransactionScope()) { //using (var conn = new OracleConnection("DATA SOURCE=//192.168.0.11/YUNSH;PASSWORD=jooge2012;PERSIST SECURITY INFO=True;USER ID=TERRY_1116;")) //{ using (var scope = DbScope.Create()) { var context = scope.DbContexts.Get <FreeDbContext>(); modelInContext = DbScope.Parse(context, shop); //modelInContext = context.Shop.Add(shop); modelInContext.ShCode = txtCode.Text; modelInContext.ShName = txtName.Text; modelInContext.ShDomainId = Guid.Empty; string sql = "select getidentitycode() from dual"; var conn = context.Database.Connection as OracleConnection; var cmd = new OracleCommand(sql, conn); if (conn.State == ConnectionState.Closed) { conn.Open(); } var obj = cmd.ExecuteScalar(); modelInContext.ShIdentityCode = obj.ToString(); scope.SaveChanges(); using (var trans2 = new TransactionScope(TransactionScopeOption.Suppress)) { try { sql = string.Format("insert into t1 values('{0}')", DateTime.Now); var conn2 = new OracleConnection( "DATA SOURCE=//192.168.0.11/YUNSH;PASSWORD=jooge2012;PERSIST SECURITY INFO=True;USER ID=TERRY_1116;"); if (conn2.State == ConnectionState.Closed) { conn2.Open(); } cmd = new OracleCommand(sql, conn2); var t = cmd.ExecuteNonQuery(); trans2.Complete(); } catch (Exception ex) { MessageBox.Show(ex.Message); } } } trans.Complete(); } //} }
public void SaveCategory(SaveCategoryParameter param) { using (var scope = DbScope.Create()) using (var context = base.CreateContext()) { scope.BeginTransaction(); if (param.ParentID > 0 && context.News.Any(t => t.CategoryID == param.ParentID)) { throw new InvalidInvokeException("不能更新有新闻的父分类"); } NewsCategory pObj; if (param.RowID > 0) { pObj = context.NewsCategories.Single(t => t.RowID == param.RowID); EntityMapper.Map <SaveCategoryParameter, NewsCategory>(param, pObj); } else { context.NewsCategories.Add(pObj = new NewsCategory()); EntityMapper.Map <SaveCategoryParameter, NewsCategory>(param, pObj); bool isTop = pObj.ParentID == 0; if (isTop) { pObj.Path = string.Empty; } else { var paramSet = GetDeepParentID(pObj.ParentID, true); pObj.Path = string.Join(",", paramSet); } if (!isTop) { pObj.Path += ","; } pObj.Path += pObj.RowID.ToString(); param.RowID = pObj.RowID; } context.SaveChanges(); //开始执行Path迁移 string sPath = string.Format(",{0},", param.RowID); var q = from t in context.NewsCategories where t.AppID == param.AppID && t.Path.Contains(sPath) select t; int level; var path = new StringBuilder(); foreach (var item in q) { if (item.ParentID == 0) { item.Path = item.RowID.ToString(); } else { level = 0; path.Length = 0; var current = item; do { level++; path.Insert(0, "," + current.RowID.ToString()); }while ((current = context.NewsCategories.Where(t => t.RowID == param.ParentID).Single()).ParentID != 0); path.Insert(0, current.RowID); item.Level = level; item.Path = path.ToString(); } } context.SaveChanges(); scope.Complete(); } CacheInterceptorAttribute.ClearCache(_QueryCategories); }