protected override void InitData() { base.InitData(); if (Meta.Count > 0) { return; } if (XTrace.Debug) { XTrace.WriteLine("开始初始化{0}菜单数据……", typeof(TEntity).Name); } using (var trans = new EntityTransaction <TEntity>()) { // 准备增加Admin目录下的所有页面 ScanAndAdd(); trans.Commit(); if (XTrace.Debug) { XTrace.WriteLine("完成初始化{0}菜单数据!", typeof(TEntity).Name); } } }
static public void Transactions() { //<snippetTransactionsWithEntityClient> using (EntityConnection con = new EntityConnection("name=AdventureWorksEntities")) { con.Open(); EntityTransaction transaction = con.BeginTransaction(); DbCommand cmd = con.CreateCommand(); cmd.Transaction = transaction; cmd.CommandText = @"SELECT VALUE Contact FROM AdventureWorksEntities.Contacts AS Contact WHERE Contact.LastName = @ln"; EntityParameter param = new EntityParameter(); param.ParameterName = "ln"; param.Value = "Adams"; cmd.Parameters.Add(param); using (DbDataReader rdr = cmd.ExecuteReader(CommandBehavior.SequentialAccess)) { // Iterate through the collection of Contact items. while (rdr.Read()) { Console.Write("First Name: " + rdr["FirstName"]); Console.WriteLine("\tLast Name: " + rdr["LastName"]); } } transaction.Commit(); } //</snippetTransactionsWithEntityClient> }
public static void PostIssue(int issueId) { // Open a connection manualy since EF has issues with MSDTC transactions var connection = new EntityConnection(ConfigurationManager.ConnectionStrings[INVENTORY_CONNECTION].ConnectionString); connection.Open(); var context = new InventoryEntities(connection); var issue = context.Issues.Single(i => i.IssueId == issueId); var warehouse = issue.WarehouseId; try { using (EntityTransaction scope = connection.BeginTransaction()) { foreach (var item in issue.IssueItems) { // 1. Check the availablity of stock (ItemId and WarehouseId) var stock = context.StockStatus.Single(s => s.ItemId == item.ItemId && s.WarehouseId == warehouse); // 2. If availalbe < requested then throw an error if (stock.Quantity < item.Quantity) { var msg = "Error posting current record. The requested and available quantity do not match.\n"; msg += string.Format("Item: {0} \nAvailable Quantity: {1}\nRequested Quantity:{2}", item.ItemDetail.ItemNo, stock.Quantity, item.Quantity); throw new ApplicationException(msg); } // 3. If available > requested then update balance and set status of issue to posted. var status = context.StockStatus.Single(s => s.ItemId == item.ItemId && s.WarehouseId == warehouse); status.Quantity -= item.Quantity; // 4. Add transaction log to stock_transaction var transaction = new StockTransaction(); transaction.TransactionTypeId = OWNER_ISSUE; transaction.OwnerId = issue.IssueId; transaction.ItemId = item.ItemId; transaction.Quantity = item.Quantity; transaction.WarehouseId = warehouse; transaction.TransactionDate = DateTime.Now; AddTransactionRecord(transaction); issue.StatusId = STATUS_POSTED; issue.PostedDate = DateTime.Now; //TODO: Consider getting the date from the server instead of the client. var user = SecurityHelper.GetUserDetail(Thread.CurrentPrincipal.Identity.Name); issue.PostedBy = string.Format("{0} ({1})", user.FullName, user.UserName); // SEND ALL CHANGES TO THE DATABASE - MIGHTY SAVE!!!!!! context.SaveChanges(); scope.Commit(); } } } catch (Exception exception) { throw new ApplicationException("Error occured while posting the current issue.", exception); } }
public void example() { using (TransactionScope mainScope = new TransactionScope()) { // ADO.NET using (SqlConnection firstConnection = new SqlConnection("First")) { firstConnection.Open(); using (SqlCommand firstCommand = new SqlCommand("FirstQueryText", firstConnection)) { Int32 recordsAffected = firstCommand.ExecuteNonQuery(); } using (SqlConnection secondConnection = new SqlConnection("Second")) { secondConnection.Open(); using (SqlCommand secondCommand = new SqlCommand("SecondQueryText", secondConnection)) { Int32 secondAffected = secondCommand.ExecuteNonQuery(); } } } mainScope.Complete(); } //Entity Connection using (TestEntities database = new TestEntities()) { Customer cust = new Customer(); cust.FirstName = "Ronald"; cust.LastName = "McDonald"; cust.AccountId = 3; database.Customers.Add(cust); database.SaveChanges(); } using (EntityConnection connection = new EntityConnection("TestEntities")) { using (EntityTransaction trans = connection.BeginTransaction(System.Data.IsolationLevel.Serializable)) { EntityCommand CurrentCommand = new EntityCommand("SOME UPDATE STATEMENT", connection, trans); connection.Open(); Int32 RecordsAffected = CurrentCommand.ExecuteNonQuery(); trans.Commit(); } } SqlConnection myConnection = new SqlConnection("Connection String"); }
/// <summary>删除用户</summary> /// <param name="uid"></param> /// <param name="delposts"></param> /// <param name="delpms"></param> /// <returns></returns> public Boolean Delete(Boolean delposts, Boolean delpms) { var user = this; using (var tran = new EntityTransaction <User>()) { user.Delete(); var tps = Topic.FindAllByPosterID(user.ID); var lps = Topic.FindAllByLastPostID(user.ID); if (delposts) { tps.Delete(); lps.Delete(); var ps = Post.FindAllByPosterID(user.ID); ps.Delete(); } else { tps.SetItem(Topic._.Poster, "该用户已被删除"); lps.SetItem(Topic._.LastPoster, "该用户已被删除"); tps.Save(); lps.Save(); } var pms1 = ShortMessage.FindAllByMsgtoID(user.ID); var pms2 = ShortMessage.FindAllByMsgfromID(user.ID); if (delpms) { pms1.Delete(); pms2.Delete(); } else { pms1.SetItem(ShortMessage._.Msgto, "该用户已被删除"); pms2.SetItem(ShortMessage._.Msgfrom, "该用户已被删除"); pms1.Save(); pms2.Save(); } tran.Commit(); } return(true); }
/// <summary>导入</summary> public virtual void Import() { using (var trans = new EntityTransaction <TEntity>()) { //顶级节点根据名字合并 if (ParentID == 0) { var m = Find(__.Name, Name); if (m != null) { this.ID = m.ID; this.Name = m.Name; this.ParentID = 0; this.Url = m.Url; this.Remark = m.Remark; this.Update(); } else { this.Insert(); } } else { this.Insert(); } //更新编号 var list = Childs; if (list != null && list.Count > 0) { foreach (TEntity item in list) { item.ParentID = ID; item.Import(); } } trans.Commit(); } }
protected override void OnPreLoad(EventArgs e) { base.OnPreLoad(e); IManageUser user = ManageProvider.Provider.Current; if (user == null) { Response.Redirect("Login.aspx"); } ICommonManageProvider provider = CommonManageProvider.Provider; IMenu root = null; if (provider != null) { root = provider.MenuRoot; } IAdministrator admin = user as IAdministrator; if (admin == null) { if (root != null) { menuItem.DataSource = root.Childs; menuItem.DataBind(); } return; } if (Request["act"] == "logout") { admin.Logout(); // 再跳一次,除去Url中的尾巴 if (!String.IsNullOrEmpty(Request.Url.Query)) { Response.Redirect("Default.aspx"); } } if (admin.Role != null) { //List<IMenu> list = admin.Role.GetMySubMenus(root.ID); IList <IMenu> list = provider.GetMySubMenus(root.ID); menuItem.DataSource = list; menuItem.DataBind(); if (list != null && list.Count > 0) { IMenu first = list[0]; DefaultLeft = String.Format("Frame/Left.aspx?ID={0}", first.ID); DefaultMain = first.Url; } } #region 自动修正菜单 // 自动修正菜单中英文 if (root != null) { using (EntityTransaction trans = new EntityTransaction(EntityFactory.CreateOperate(root.GetType()))) { root.CheckMenuName("Admin", "管理平台") .CheckMenuName(@"Admin\Sys", "系统管理") .CheckMenuName(@"Admin\Advance", "高级设置") .CheckMenuName(@"Admin\Help", "帮助手册"); // 自动挂载Main.aspx IMenu menu = root.FindByPath("Admin"); if (menu != null && menu.Url == "../Admin/Default.aspx") { menu.Url = "../Admin/Main.aspx"; menu.Save(); } if (menu != null) { #region 自动排序 IMenu menu2 = menu.FindByPath("Sys"); if (menu2 != null) { menu2.Sort = 3; menu2.Save(); } menu2 = menu.FindByPath("Advance"); if (menu2 != null) { menu2.Sort = 2; menu2.Save(); } menu2 = menu.FindByPath("Help"); if (menu2 != null) { menu2.Sort = 1; menu2.Save(); } #endregion } trans.Commit(); } } #endregion }
/// <summary> /// Commits the underlying store transaction /// </summary> public void Commit() { _entityTransaction.Commit(); }
static void TestInsert() { // 关闭SQL日志 XCode.Setting.Current.ShowSQL = false; Console.WriteLine(Trade.Meta.Count); // 准备数据 var list = new List <Trade>(); Console.Write("正在准备数据:"); for (int i = 0; i < 100000; i++) { if (i % 1000 == 0) { Console.Write("."); } var td = new Trade(); foreach (var item in Trade.Meta.Fields) { if (item.IsIdentity) { continue; } if (item.Type == typeof(Int32)) { td.SetItem(item.Name, Rand.Next()); } else if (item.Type == typeof(String)) { td.SetItem(item.Name, Rand.NextString(8)); } } list.Add(td); } Console.WriteLine(); Console.WriteLine("数据准备完毕!"); var sw = new Stopwatch(); sw.Start(); Console.Write("正在准备写入:"); EntityTransaction tr = null; for (int i = 0; i < list.Count; i++) { if (i % 1000 == 0) { Console.Write("."); if (tr != null) { tr.Commit(); } tr = Trade.Meta.CreateTrans(); } list[i].SaveWithoutValid(); } if (tr != null) { tr.Commit(); } sw.Stop(); Console.WriteLine("数据写入完毕!"); var ms = sw.ElapsedMilliseconds; Console.WriteLine("耗时:{0:n0}ms 平均速度:{1:n0}tps", ms, list.Count * 1000L / ms); }
//This is not working //TODO: Fix syntax of updateCommand private void UpdateUsingEntityCommand(User entity) { using (EntityConnection entityConnection = new EntityConnection("name=AppEntities")) { entityConnection.Open(); using (EntityTransaction entityTransaction = entityConnection.BeginTransaction(IsolationLevel.Serializable)) { string updateCommand = "UPDATE AppEntities.USERS AS U " + "SET U.FirstName = @FirstName, " + "U.LastName = @lastName, " + "U.Username = @userName, " + "U.City = @city " + "WHERE U.Id = @Id"; using (EntityCommand command = new EntityCommand(updateCommand, entityConnection, entityTransaction)) { EntityParameter firstName = new EntityParameter() { ParameterName = "firstName", Value = entity.FirstName }; EntityParameter lastName = new EntityParameter() { ParameterName = "lastName", Value = entity.LastName }; EntityParameter username = new EntityParameter() { ParameterName = "username", Value = entity.Username }; EntityParameter city = new EntityParameter() { ParameterName = "city", Value = entity.City }; EntityParameter id = new EntityParameter() { ParameterName = "Id", Value = entity.Id }; command.Parameters.Add(firstName); command.Parameters.Add(lastName); command.Parameters.Add(username); command.Parameters.Add(city); command.Parameters.Add(id); try { command.ExecuteNonQuery(); entityTransaction.Commit(); } catch (Exception ex) { entityTransaction.Rollback(); } } } } }
private void ProcessPackageEdits(IEnumerable <PackageEdit> editsForThisPackage, EntitiesContext entitiesContext) { // List of Work to do: // 1) Backup old blob, if the original has not been backed up yet // 2) Downloads blob, create new NUPKG locally // 3) Upload blob // 4) Update the database PackageEdit edit = editsForThisPackage.OrderByDescending(pe => pe.Timestamp).First(); var blobClient = StorageAccount.CreateCloudBlobClient(); var packagesContainer = Util.GetPackagesBlobContainer(blobClient); var latestPackageFileName = Util.GetPackageFileName(edit.Package.PackageRegistration.Id, edit.Package.Version); var originalPackageFileName = Util.GetBackupOfOriginalPackageFileName(edit.Package.PackageRegistration.Id, edit.Package.Version); var originalPackageBackupBlob = packagesContainer.GetBlockBlobReference(originalPackageFileName); var latestPackageBlob = packagesContainer.GetBlockBlobReference(latestPackageFileName); var edits = new List <Action <ManifestMetadata> > { (m) => { m.Authors = edit.Authors; }, (m) => { m.Copyright = edit.Copyright; }, (m) => { m.Description = edit.Description; }, (m) => { m.IconUrl = edit.IconUrl; }, (m) => { m.LicenseUrl = edit.LicenseUrl; }, (m) => { m.ProjectUrl = edit.ProjectUrl; }, (m) => { m.ReleaseNotes = edit.ReleaseNotes; }, (m) => { m.RequireLicenseAcceptance = edit.RequiresLicenseAcceptance; }, (m) => { m.Summary = edit.Summary; }, (m) => { m.Title = edit.Title; }, (m) => { m.Tags = edit.Tags; }, }; Log.Info( "Processing Edit Key={0}, PackageId={1}, Version={2}", edit.Key, edit.Package.PackageRegistration.Id, edit.Package.Version); if (!WhatIf) { edit.TriedCount += 1; int nr = entitiesContext.SaveChanges(); if (nr != 1) { throw new ApplicationException( String.Format("Something went terribly wrong, only one entity should be updated but actually {0} entities were updated", nr)); } } ArchiveOriginalPackageBlob(originalPackageBackupBlob, latestPackageBlob); using (var readWriteStream = new MemoryStream()) { // Download to memory CloudBlockBlob downloadSourceBlob = WhatIf ? latestPackageBlob : originalPackageBackupBlob; Log.Info("Downloading original package blob to memory {0}", downloadSourceBlob.Name); downloadSourceBlob.DownloadToStream(readWriteStream); // Rewrite in memory Log.Info("Rewriting nupkg package in memory", downloadSourceBlob.Name); NupkgRewriter.RewriteNupkgManifest(readWriteStream, edits); // Get updated hash code, and file size Log.Info("Computing updated hash code of memory stream"); var newPackageFileSize = readWriteStream.Length; var hashAlgorithm = HashAlgorithm.Create("SHA512"); byte[] hashBytes = hashAlgorithm.ComputeHash(readWriteStream.GetBuffer()); var newHash = Convert.ToBase64String(hashBytes); if (!WhatIf) { // Snapshot the blob var blobSnapshot = latestPackageBlob.CreateSnapshot(); // Start Transaction: Complete the edit in the gallery DB. // Use explicit SQL transactions instead of EF operation-grouping // so that we can manually roll the transaction back on a blob related failure. ObjectContext objectContext = (entitiesContext as IObjectContextAdapter).ObjectContext; ((objectContext.Connection) as EntityConnection).Open(); // must open in order to begin transaction using (EntityTransaction transaction = ((objectContext.Connection) as EntityConnection).BeginTransaction()) { edit.Apply(hashAlgorithm: "SHA512", hash: newHash, packageFileSize: newPackageFileSize); // Add to transaction: delete all the pending edits of this package. foreach (var eachEdit in editsForThisPackage) { entitiesContext.DeleteOnCommit(eachEdit); } entitiesContext.SaveChanges(); // (transaction is still not committed, but do some EF legwork up-front of modifying the blob) try { // Reupload blob Log.Info("Uploading blob from memory {0}", latestPackageBlob.Name); readWriteStream.Position = 0; latestPackageBlob.UploadFromStream(readWriteStream); } catch (Exception e) { // Uploading the updated nupkg failed. // Rollback the transaction, which restores the Edit to PackageEdits so it can be attempted again. Log.Error("(error) - package edit blob update failed. Rolling back the DB transaction."); Log.ErrorException("(exception", e); Log.Error("(note) - blob snapshot URL = " + blobSnapshot.Uri); transaction.Rollback(); return; } try { transaction.Commit(); } catch (Exception e) { // Commit changes to DB failed. // Since our blob update wasn't part of the transaction (and doesn't AFAIK have a 'commit()' operator we can utilize for the type of blobs we are using) // try, (single attempt) to roll back the blob update by restoring the previous snapshot. Log.Error("(error) - package edit DB update failed. Trying to roll back the blob to its previous snapshot."); Log.ErrorException("(exception", e); Log.Error("(note) - blob snapshot URL = " + blobSnapshot.Uri); try { latestPackageBlob.StartCopyFromBlob(blobSnapshot); } catch (Exception e2) { // In this case it may not be the end of the world - the package metadata mismatches the edit now, // but there's still an edit in the queue, waiting to be rerun and put everything back in synch. Log.Error("(error) - rolling back the package blob to its previous snapshot failed."); Log.ErrorException("(exception", e2); Log.Error("(note) - blob snapshot URL = " + blobSnapshot.Uri); } } } } } }
public static void PostAdjustment(int adjustmentId) { var connection = new EntityConnection(ConfigurationManager.ConnectionStrings[INVENTORY_CONNECTION].ConnectionString); connection.Open(); var context = new InventoryEntities(connection); var adjust = context.Adjustments.Single(r => r.AdjustmentId == adjustmentId); try { using (EntityTransaction scope = connection.BeginTransaction()) { foreach (var item in adjust.adjustment_detail) { // Checking if the current item already exists in the 'stock_status' table if ( !context.StockStatus.Where( s => s.ItemId == item.ItemId && s.WarehouseId == adjust.WarehouseId). Any()) { using (var c = new InventoryEntities()) { var status = new StockStatus(); status.ItemId = item.ItemId.Value; status.WarehouseId = adjust.WarehouseId.Value; status.Quantity = item.AdjustedQuantity; c.StockStatus.AddObject(status); c.SaveChanges(); } } // If the item already exists in the table then update the quantity field var statusUpdate = context.StockStatus.SingleOrDefault( s => s.ItemId == item.ItemId && s.WarehouseId == adjust.WarehouseId); statusUpdate.Quantity = item.AdjustedQuantity; // Adding to stock transaction log var transaction = new StockTransaction(); transaction.TransactionTypeId = OWNER_ADJUSTMENT; transaction.OwnerId = adjust.AdjustmentId; transaction.ItemId = item.ItemId; transaction.Quantity = item.AdjustedQuantity; transaction.WarehouseId = adjust.WarehouseId; transaction.TransactionDate = DateTime.Now; AddTransactionRecord(transaction); adjust.StatusId = STATUS_POSTED; adjust.PostedDate = DateTime.Now; var user = SecurityHelper.GetUserDetail(Thread.CurrentPrincipal.Identity.Name); adjust.PostedBy = string.Format("{0} ({1})", user.FullName, user.UserName); // SEND ALL CHANGES TO THE DATABASE - MIGHTY SAVE!!!!!! context.SaveChanges(); scope.Commit(); } connection.Close(); } } catch (Exception exception) { throw new ApplicationException("Unable to post adjustment", exception); } }
public static void PostTransfer(int transferId) { // Open a connection manualy since EF has issues with MSDTC transactions var connection = new EntityConnection(ConfigurationManager.ConnectionStrings[INVENTORY_CONNECTION].ConnectionString); connection.Open(); var context = new InventoryEntities(connection); // Tasks: // 1. Check if requested transfer amount exist at the source warehouse // 2. Check if transfered item exist in stock status @ destination warehouse // 3. Decrease source warehouse balance and increase destination warehouse // 4. Post transfer record and update audit log. var transfer = context.Transfers.Single(t => t.TransferId == transferId); var source = transfer.WarehouseFrom; var destination = transfer.WarehouseTo; try { using (EntityTransaction scope = connection.BeginTransaction()) { foreach (var item in transfer.TransferItems) { var itemId = item.ItemId; // Check if requested transfer amount exist in source warehouse. var sourceStatus = context.StockStatus.Single( s => s.ItemId == itemId && s.WarehouseId == source); if (sourceStatus.Quantity < item.Quantity) { throw new ApplicationException( "The current balance at the source warehouse is less than the requested transfer amount."); } // Check if we have a stock status record at the destination warehouse with the current item id. If not then we need to create one. if (!context.StockStatus.Where(s => s.ItemId == itemId && s.WarehouseId == destination).Any()) { using (var c = new InventoryEntities()) { var status = new StockStatus(); status.ItemId = itemId.Value; status.WarehouseId = destination.Value; status.Quantity = 0; c.StockStatus.AddObject(status); c.SaveChanges(); } } // Decrease the quantity field for the source status update and increase that of the destination status update var sourceStatusUpdate = context.StockStatus.SingleOrDefault( s => s.ItemId == itemId && s.WarehouseId == source); sourceStatusUpdate.Quantity -= item.Quantity; var destinationStatusUpdate = context.StockStatus.SingleOrDefault( d => d.ItemId == itemId && d.WarehouseId == destination); destinationStatusUpdate.Quantity += item.Quantity; // Add transaction log var transaction = new StockTransaction(); transaction.TransactionTypeId = OWNER_TRANSFER; transaction.OwnerId = transfer.TransferId; transaction.ItemId = itemId; transaction.Quantity = item.Quantity; transaction.WarehouseId = transfer.WarehouseFrom; transaction.TransactionDate = DateTime.Now; AddTransactionRecord(transaction); } // Update PostedDate and PostedBy fields for the Receiving record transfer.StatusId = STATUS_POSTED; transfer.PostedDate = DateTime.Now; //TODO: Consider getting the date from the server instead of the client. var user = SecurityHelper.GetUserDetail(Thread.CurrentPrincipal.Identity.Name); transfer.PostedBy = string.Format("{0} ({1})", user.FullName, user.UserName); // SEND ALL CHANGES TO THE DATABASE - MIGHTY SAVE!!!!!! context.SaveChanges(); scope.Commit(); } } catch (Exception exception) { throw new ApplicationException("Error occured while posting stock transfer operation.", exception); } connection.Close(); }
public static void PostReturn(int returnId) { // Open a connection manualy since EF has issues with MSDTC transactions var connection = new EntityConnection(ConfigurationManager.ConnectionStrings[INVENTORY_CONNECTION].ConnectionString); connection.Open(); var context = new InventoryEntities(connection); var returnItem = context.ItemReturns.Single(r => r.ReturnId == returnId); try { using (EntityTransaction scope = connection.BeginTransaction()) { foreach (var item in returnItem.ReturnedItems) { // Check if the current item already exists in the 'stock_status' table if (!context.StockStatus.Where(s => s.ItemId == item.ItemId && s.WarehouseId == returnItem.WarehouseId).Any()) { using (var c = new InventoryEntities()) { var status = new StockStatus(); status.ItemId = item.ItemId.Value; status.WarehouseId = returnItem.WarehouseId.Value; status.Quantity = 0; c.StockStatus.AddObject(status); c.SaveChanges(); } } // If the item already exists in the table then update the quantity field var statusUpdate = context.StockStatus.SingleOrDefault( s => s.ItemId == item.ItemId && s.WarehouseId == returnItem.WarehouseId); statusUpdate.Quantity += item.Quantity; // Add transaction log var transaction = new StockTransaction(); transaction.TransactionTypeId = OWNER_RETURN; transaction.OwnerId = returnItem.ReturnId; transaction.ItemId = item.ItemId; transaction.Quantity = item.Quantity; transaction.WarehouseId = returnItem.WarehouseId; transaction.TransactionDate = DateTime.Now; AddTransactionRecord(transaction); } // Update PostedDate and PostedBy fields for the Receiving record returnItem.StatusId = STATUS_POSTED; returnItem.PostedDate = DateTime.Now; //TODO: Consider getting the date from the server instead of the client. var user = SecurityHelper.GetUserDetail(Thread.CurrentPrincipal.Identity.Name); returnItem.PostedBy = string.Format("{0} ({1})", user.FullName, user.UserName); // SEND ALL CHANGES TO THE DATABASE - MIGHTY SAVE!!!!!! context.SaveChanges(); scope.Commit(); } } catch (Exception exception) { throw new ApplicationException("Error occured while posting stock return operation.", exception); } // Close the connection connection.Close(); }
/// <summary>导入</summary> /// <param name="reader"></param> public static void Import(StreamReader reader) { using (var trans = new EntityTransaction <TEntity>()) { while (!reader.EndOfStream) { String context = reader.ReadLine(); if (String.IsNullOrEmpty(context)) { break; } String[] ss = context.Split(new Char[] { ' ' }); TEntity entity = new TEntity(); Int32 code = Int32.Parse(ss[0]); entity.Code = code; Int32 oldcode = Int32.Parse(ss[1]); if (code != oldcode) { entity.OldCode = oldcode; } Int32 oldcode2 = Int32.Parse(ss[2]); if (code != oldcode2) { entity.OldCode2 = oldcode2; } Int32 oldcode3 = Int32.Parse(ss[3]); if (code != oldcode3) { entity.OldCode3 = oldcode3; } entity.Name = ss[4]; if (ss.Length > 5) { entity.Description = ss[5]; } // 查找父级地区 if (code % 10000 == 0) { entity.ParentCode = 0; } else if (code % 100 == 0) { entity.ParentCode = code / 10000; entity.ParentCode = entity.ParentCode * 10000; } else { entity.ParentCode = code / 100; entity.ParentCode = entity.ParentCode * 100; } entity.SaveWithoutValid(); } trans.Commit(); } }