Task <IEnumerable <SynchronousDb> > IQueryRepostry <SynchronousDb, int> .GetItemsAsync() { using (DataSyncContext context = new DataSyncContext()) { return(Task.FromResult((IEnumerable <SynchronousDb>)context.SynchronousDb.ToList())); } }
public SynchronousDb GetItemByID(int id) { using (DataSyncContext context = new DataSyncContext()) { return(context.SynchronousDb.Where(c => c.ID == id).FirstOrDefault()); } }
public Task <SourceTable> GetItemsByIDAsync(int id) { using (DataSyncContext context = new DataSyncContext()) { return(Task.FromResult(context.SourceTables.Where(c => c.ID == id).FirstOrDefault())); } }
protected override DataSyncContext CreateDataContext() { var context = new DataContext(); //These columns cannot be added in the strongly-typed row //because the People table must be usable without pledges //or payments. (eg, ListMaker or Rafflizer) if (!Person.Schema.Columns.Contains("TotalPaid")) //This can be called multiple times in the designer AppDomain { Person.Schema.Columns.AddCalculatedColumn <Person, decimal>("TotalPaid", person => person.Payments.Sum(p => p.Amount)); Person.Schema.Columns.AddCalculatedColumn <Person, decimal>("TotalPledged", person => person.Pledges.Sum(p => p.Amount)); Person.Schema.Columns.AddCalculatedColumn <decimal>("BalanceDue", person => person.Field <decimal>("TotalPledged") - person.Field <decimal>("TotalPaid")); Payment.Schema.Columns.RemoveColumn(Payment.DepositColumn); ValueColumn uiidColumn = Person.Schema.Columns.AddValueColumn(nameof(Extensions.UIId), typeof(int?), null); Person.SchemaMapping.Columns.RemoveMapping(uiidColumn); } context.Tables.AddTable(Pledge.CreateTable()); context.Tables.AddTable(Payment.CreateTable()); context.Tables.AddTable(EmailAddress.CreateTable()); context.Tables.AddTable(Person.CreateTable()); var dsc = new DataSyncContext(context, new SqlServerSqlProvider(DB.Default)); dsc.Tables.AddPrimaryMappings(); return(dsc); }
public Task <IEnumerable <SourceTable> > GetItemsAsync() { using (DataSyncContext context = new DataSyncContext()) { return(Task.FromResult((IEnumerable <SourceTable>)context.SourceTables)); } }
public IEnumerable <SourceTable> GetItems() { using (DataSyncContext context = new DataSyncContext()) { return(context.SourceTables); } }
protected override DataSyncContext CreateDataContext() { var context = new DataContext(); context.Tables.AddTable(Person.CreateTable()); var dsc = new DataSyncContext(context, new SqlServerSqlProvider(DB.Default)); dsc.Tables.AddPrimaryMappings(); return dsc; }
///<summary>Creates the tables needed in a database.</summary> public static void SetupDatabase(DataSyncContext context) { using (var connection = context.SqlProvider.OpenConnection()) foreach (var table in context.Tables.SortDependencies(ts => ts.Mapping.Schema)) { context.SqlProvider.CreateTable(connection, table.Mapping, context.Tables.Select(ts => ts.Mapping)); } }
protected override DataSyncContext CreateDataContext() { var context = new DataContext(); context.Tables.AddTable(Person.CreateTable()); var dsc = new DataSyncContext(context, new SqlServerSqlProvider(DB.Default)); dsc.Tables.AddPrimaryMappings(); return(dsc); }
public bool UpLoad([FromBody] UpdateFormData info) { if (info != null) { return(DataSyncContext.UpLoadAll(info)); } else { return(false); } }
DataSyncContext CreateServerContext() { var context = new DataContext(); var syncContext = new DataSyncContext(context, new SqlServerSqlProvider(databases.SelectedConnector)); //Add all of the tables that we actually use. foreach (var ts in Program.Current.SyncContext.Tables.SortDependencies(ts => ts.Table.Schema)) { var table = ts.Table.Schema.CreateTable(); context.Tables.AddTable(table); syncContext.Tables.AddMapping(ts.Mapping); } ProgressWorker.Execute(ui => { ui.Caption = "Reading " + databases.SelectedItem.Caption; syncContext.ReadData(); }, cancellable: false); return syncContext; }
public UpdateFormData Download([FromBody] UpdateFormData info) { if (info != null) { try { return(DataSyncContext.DownloadAll(info)); } catch (Exception) { return(null); } } else { return(null); } }
DataSyncContext CreateServerContext() { var context = new DataContext(); var syncContext = new DataSyncContext(context, new SqlServerSqlProvider(databases.SelectedConnector)); //Add all of the tables that we actually use. foreach (var ts in Program.Current.SyncContext.Tables.SortDependencies(ts => ts.Table.Schema)) { var table = ts.Table.Schema.CreateTable(); context.Tables.AddTable(table); syncContext.Tables.AddMapping(ts.Mapping); } ProgressWorker.Execute(ui => { ui.Caption = "Reading " + databases.SelectedItem.Caption; syncContext.ReadData(); }, cancellable: false); return(syncContext); }
protected override DataSyncContext CreateDataContext() { var dc = new DataContext(); dc.Tables.AddTable(Person.CreateTable()); dc.Tables.AddTable(RaffleTicket.CreateTable()); var dsc = new DataSyncContext(dc, new SqlCeSqlProvider(FilePath)); dsc.Tables.AddPrimaryMappings(); if (!File.Exists(FilePath)) { DB.CreateFile(FilePath, DatabaseFile.SqlCe); try { DBManager.SetupDatabase(dsc); } catch { File.Delete(FilePath); } } return dsc; }
public Task <bool> Update(SourceTable model, Action <SourceTable, Exception> callBack) { bool result = false; try { using (DataSyncContext context = new DataSyncContext()) { context.Entry <SourceTable>(model).State = System.Data.Entity.EntityState.Modified; result = context.SaveChanges() > 0?true:false; } callBack(model, null); } catch (Exception ex) { callBack(model, ex); } return(Task.FromResult(result)); }
public Task <bool> Add(SourceTable model, Action <SourceTable, Exception> callBack) { bool result = false; try { using (DataSyncContext context = new DataSyncContext()) { context.SourceTables.Add(model); result = context.SaveChanges() > 0?true:false; } callBack(model, null); } catch (Exception ex) { callBack(model, ex); } return(Task.FromResult <bool>(result)); }
public Task <bool> Delete(int key, Action <int, Exception> callBack) { bool result = false; try { using (DataSyncContext context = new DataSyncContext()) { context.SynchronousDb.Where(c => c.ID == key).Delete(); result = context.SaveChanges() > 0 ? true : false; } callBack(key, null); } catch (Exception ex) { callBack(key, ex); } return(Task.FromResult(result)); }
Task <bool> IUpdateRepostry <SynchronousDb, int> .Add(SynchronousDb model, Action <SynchronousDb, Exception> callBack) { bool result = false; try { using (DataSyncContext context = new DataSyncContext()) { context.SynchronousDb.Add(model); result = context.SaveChanges() > 0?true:false; } callBack(model, null); } catch (Exception ex) { callBack(model, ex); } return(Task.FromResult(result)); }
protected override DataSyncContext CreateDataContext() { var context = new DataContext(); //These columns cannot be added in the strongly-typed row //because the People table must be usable without pledges //or payments. (eg, ListMaker or Rafflizer) if (!Person.Schema.Columns.Contains("TotalPaid")) //This can be called multiple times in the designer AppDomain { Person.Schema.Columns.AddCalculatedColumn <Person, decimal>("TotalPaid", person => person.Payments.Sum(p => p.Amount)); Person.Schema.Columns.AddCalculatedColumn <Person, decimal>("TotalPledged", person => person.Pledges.Sum(p => p.Amount)); Person.Schema.Columns.AddCalculatedColumn <decimal>("BalanceDue", person => person.Field <decimal>("TotalPledged") - person.Field <decimal>("TotalPaid")); Pledge.Schema.Columns.AddCalculatedColumn <Pledge, decimal>("UnlinkedAmount", p => p.Amount <= 0 ? 0 : p.Amount - p.LinkedPayments.Sum(o => o.Amount)); EmailAddress.PersonColumn.AddIndex(); Pledge.PersonColumn.AddIndex(); Payment.PersonColumn.AddIndex(); PledgeLink.PaymentColumn.AddIndex(); PledgeLink.PledgeColumn.AddIndex(); } context.Tables.AddTable(PledgeLink.CreateTable()); context.Tables.AddTable(Payment.CreateTable()); context.Tables.AddTable(Pledge.CreateTable()); context.Tables.AddTable(EmailAddress.CreateTable()); context.Tables.AddTable(LoggedStatement.CreateTable()); context.Tables.AddTable(Person.CreateTable()); context.Tables.AddTable(Deposit.CreateTable()); context.Tables.AddTable(RelativeLink.CreateTable()); if (IsDesignTime) { AddDesignTimeTables(context); } var syncContext = new DataSyncContext(context, new SqlServerSqlProvider(DB.Default)); syncContext.Tables.AddPrimaryMappings(); return(syncContext); }
Task <bool> IUpdateRepostry <SynchronousDb, int> .Update(SynchronousDb model, Action <SynchronousDb, Exception> callBack) { bool result = false; try { using (DataSyncContext context = new DataSyncContext()) { //var obj=context.SynchronousDb.Where(c => c.ID == model.ID).FirstOrDefault(); // obj = AutoMapper.Mapper.Map<SynchronousDb>(model); context.Entry <SynchronousDb>(model).State = System.Data.Entity.EntityState.Modified; result = context.SaveChanges() > 0?true:false; callBack(model, null); } } catch (Exception ex) { callBack(model, ex); } return(Task.FromResult(result)); }
protected override DataSyncContext CreateDataContext() { var dc = new DataContext(); dc.Tables.AddTable(Person.CreateTable()); dc.Tables.AddTable(RaffleTicket.CreateTable()); var dsc = new DataSyncContext(dc, new SqlCeSqlProvider(FilePath)); dsc.Tables.AddPrimaryMappings(); if (!File.Exists(FilePath)) { DB.CreateFile(FilePath, DatabaseFile.SqlCe); try { DBManager.SetupDatabase(dsc); } catch { File.Delete(FilePath); } } return(dsc); }
protected override DataSyncContext CreateDataContext() { var context = new DataContext(); //These columns cannot be added in the strongly-typed row //because the People table must be usable without pledges //or payments. (eg, ListMaker or Rafflizer) if (!Person.Schema.Columns.Contains("TotalPaid")) { //This can be called multiple times in the designer AppDomain Person.Schema.Columns.AddCalculatedColumn<Person, decimal>("TotalPaid", person => person.Payments.Sum(p => p.Amount)); Person.Schema.Columns.AddCalculatedColumn<Person, decimal>("TotalPledged", person => person.Pledges.Sum(p => p.Amount)); Person.Schema.Columns.AddCalculatedColumn<decimal>("BalanceDue", person => person.Field<decimal>("TotalPledged") - person.Field<decimal>("TotalPaid")); Payment.Schema.Columns.RemoveColumn(Payment.DepositColumn); } context.Tables.AddTable(Pledge.CreateTable()); context.Tables.AddTable(Payment.CreateTable()); context.Tables.AddTable(EmailAddress.CreateTable()); context.Tables.AddTable(Person.CreateTable()); var dsc = new DataSyncContext(context, new SqlServerSqlProvider(DB.Default)); dsc.Tables.AddPrimaryMappings(); return dsc; }
public static string Handler(short methodItem, string storeId, string exportItem, string importItem, bool zipFile = true) { string msg = ""; try { var info = new UpdateFormData(); Dictionary <string, string> filenames = new Dictionary <string, string>(); if (methodItem == 1 && !exportItem.IsNullOrEmpty()) { info.StoreId = storeId; info.Mode = DataSyncMode.FromServerDownload; var zipfileName = "未知"; switch (exportItem) { case "Notice": info.Datas["Pharos.Logic.LocalEntity.Notice"] = new List <NoticeForLocal>(); filenames["Pharos.Logic.LocalEntity.Notice"] = "公告信息"; zipfileName = "公告信息"; break; case "ApiLibrary": info.Datas["Pharos.Logic.LocalEntity.ApiLibrary"] = new List <ApiLibraryForLocal>(); filenames["Pharos.Logic.LocalEntity.ApiLibrary"] = "接口信息"; zipfileName = "接口信息"; break; case "SysStoreUserInfo": info.Datas["Pharos.Logic.LocalEntity.SysStoreUserInfo"] = new List <SysStoreUserInfoForLocal>(); filenames["Pharos.Logic.LocalEntity.SysStoreUserInfo"] = "用户信息"; zipfileName = "用户信息"; break; case "Members": info.Datas["Pharos.Logic.LocalEntity.Members"] = new List <MembersForLocal>(); filenames["Pharos.Logic.LocalEntity.Members"] = "会员信息"; zipfileName = "会员信息"; break; case "Product": info.Datas["Pharos.Logic.LocalEntity.ProductBrand"] = new List <ProductBrandForLocal>(); info.Datas["Pharos.Logic.LocalEntity.ProductCategory"] = new List <ProductCategoryForLocal>(); info.Datas["Pharos.Logic.LocalEntity.SysDataDictionary"] = new List <SysDataDictionaryForLocal>(); info.Datas["Pharos.Logic.LocalEntity.ProductInfo"] = new List <ProductInfoForLocal>(); // info.Datas["Pharos.Logic.LocalEntity.Commodity"] = new List<CommodityForLocal>(); filenames["Pharos.Logic.LocalEntity.ProductBrand"] = "品牌信息"; filenames["Pharos.Logic.LocalEntity.ProductCategory"] = "类别信息"; filenames["Pharos.Logic.LocalEntity.SysDataDictionary"] = "字典信息"; filenames["Pharos.Logic.LocalEntity.ProductInfo"] = "商品信息"; filenames["Pharos.Logic.LocalEntity.Commodity"] = "库存信息"; zipfileName = "商品信息"; break; case "Product2": info.Datas["Pharos.Logic.LocalEntity.ProductInfo2"] = new List <ProductInfoForLocal>(); filenames["Pharos.Logic.LocalEntity.ProductInfo2"] = "商品称重信息"; zipfileName = "商品称重信息"; break; case "Product3": info.Datas["Pharos.Logic.LocalEntity.ProductInfo"] = new List <ProductInfoForLocal>(); filenames["Pharos.Logic.LocalEntity.ProductInfo"] = "商品信息"; zipfileName = "商品信息"; break; case "Promotion": info.Datas["Pharos.Logic.LocalEntity.CommodityPromotion"] = new List <CommodityPromotionForLocal>(); info.Datas["Pharos.Logic.LocalEntity.Bundling"] = new List <BundlingForLocal>(); info.Datas["Pharos.Logic.LocalEntity.BundlingList"] = new List <BundlingListForLocal>(); info.Datas["Pharos.Logic.LocalEntity.CommodityDiscount"] = new List <CommodityDiscountForLocal>(); info.Datas["Pharos.Logic.LocalEntity.FreeGiftPurchase"] = new List <FreeGiftPurchaseForLocal>(); info.Datas["Pharos.Logic.LocalEntity.FreeGiftPurchaseList"] = new List <FreeGiftPurchaseListForLocal>(); info.Datas["Pharos.Logic.LocalEntity.PromotionBlend"] = new List <PromotionBlendForLocal>(); info.Datas["Pharos.Logic.LocalEntity.PromotionBlendList"] = new List <PromotionBlendListForLocal>(); filenames["Pharos.Logic.LocalEntity.CommodityPromotion"] = "主促销信息"; filenames["Pharos.Logic.LocalEntity.Bundling"] = "捆绑信息"; filenames["Pharos.Logic.LocalEntity.BundlingList"] = "捆绑商品信息"; filenames["Pharos.Logic.LocalEntity.CommodityDiscount"] = "商品折扣信息"; filenames["Pharos.Logic.LocalEntity.FreeGiftPurchase"] = "买赠信息"; filenames["Pharos.Logic.LocalEntity.FreeGiftPurchaseList"] = "买赠商品信息"; filenames["Pharos.Logic.LocalEntity.PromotionBlend"] = "组合信息"; filenames["Pharos.Logic.LocalEntity.PromotionBlendList"] = "组合商品信息"; zipfileName = "促销信息"; break; default: break; } var data = DataSyncContext.ExportAll(info); string relativePath = ""; var root = Sys.SysConstPool.SaveAttachPath(ref relativePath, "temp"); bool hasFile = false; var maxrecord = System.Web.HttpContext.Current.Request["MaxRecord"].IsNullOrEmpty() ? 0 : int.Parse(System.Web.HttpContext.Current.Request["MaxRecord"]); foreach (var de in data.Datas) { if (!de.Value.Any()) { continue; } var fileName = filenames[de.Key]; if (fileName == "商品称重信息") { var list = de.Value; var count = maxrecord % list.Count() == 0 ? list.Count() / maxrecord : list.Count() / maxrecord + 1; for (int i = 0; i < count; i++) { list = de.Value.Skip(i * maxrecord).Take(maxrecord); var fn = fileName + (i + 1) + ".txp"; CreateTxt(Path.Combine(root, fn), list, storeId); filenames[fn] = Path.Combine(root, fn); } if (count == 0) { fileName = fileName + ".txp"; CreateTxt(Path.Combine(root, fileName), list, storeId); } } else { fileName = fileName + ".xls"; Pharos.Utility.ExportExcelForCS.ToExcel <object>(fileName, root, de.Value); } filenames[de.Key] = Path.Combine(root, fileName); hasFile = true; } if (hasFile) { byte[] buffer; if (zipFile) { Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile(Encoding.UTF8); foreach (var de in filenames) { if (!File.Exists(de.Value)) { continue; } zip.AddFile(de.Value, ""); } var stream = new MemoryStream(); zip.Save(stream); zipfileName = zipfileName + ".zip"; buffer = stream.GetBuffer(); } else { var path = filenames.FirstOrDefault().Value; var stream = new FileStream(path, FileMode.Open); zipfileName = zipfileName + Path.GetExtension(path); buffer = new byte[stream.Length]; stream.Read(buffer, 0, buffer.Length); } HttpContext.Current.Response.Clear(); HttpContext.Current.Response.ClearHeaders(); HttpContext.Current.Response.ContentType = "application/octet-stream"; if (HttpContext.Current.Request.Browser.Browser.Equals("InternetExplorer", StringComparison.CurrentCultureIgnoreCase)) { HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(zipfileName)); } else { HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;fileName=" + zipfileName); } HttpContext.Current.Response.BinaryWrite(buffer); HttpContext.Current.Response.Flush(); HttpContext.Current.Response.End(); } else { msg = "该项暂无数据"; } } else if (methodItem == 2 && !importItem.IsNullOrEmpty()) { var list = new List <dynamic>(); for (int i = 0; i < HttpContext.Current.Request.Files.Count; i++) { var file = HttpContext.Current.Request.Files[i]; if (file.ContentLength <= 0) { continue; } var workbook = ExportExcelForCS.InitWorkbook(file.FileName, file.InputStream); var title = ExportExcelForCS.GetHeader(file.FileName, file.InputStream, workbook); if (title.IsNullOrEmpty()) { continue; } try { switch (importItem) { case "PosIncomePayout": list.AddRange(ExportExcelForCS.ReadListFromStream(new PosIncomePayoutForLocal(), workbook, false).Select(o => Pharos.Logic.Entity.BaseEntityExtension.InitEntity <PosIncomePayout>(o))); break; case "SalesReturns": //var key =LocalDataSyncContext.TableNames.FirstOrDefault(p => p.Value == title).Key; //var result = ExportExcelForCS.ReadListFromStream(LocalDataSyncContext.Entities[key], workbook, false); if (title.Contains("售后退换")) { list.AddRange(ExportExcelForCS.ReadListFromStream(new SalesReturnsForLocal(), workbook, false).Select(o => Pharos.Logic.Entity.BaseEntityExtension.InitEntity <SalesReturns>(o))); } if (title.Contains("换货明细")) { list.AddRange(ExportExcelForCS.ReadListFromStream(new SalesReturnsDetailedForLocal(), workbook, false).Select(o => Pharos.Logic.Entity.BaseEntityExtension.InitEntity <SalesReturnsDetailed>(o))); } break; case "SaleOrders": if (title.Contains("销售单")) { list.AddRange(ExportExcelForCS.ReadListFromStream(new SaleOrdersForLocal(), workbook, false).Select(o => Pharos.Logic.Entity.BaseEntityExtension.InitEntity <SaleOrders>(o))); } if (title.Contains("销售明细")) { list.AddRange(ExportExcelForCS.ReadListFromStream(new SaleDetailForLocal(), workbook, false).Select(o => Pharos.Logic.Entity.BaseEntityExtension.InitEntity <SaleDetail>(o))); } if (title.Contains("消费支付")) { list.AddRange(ExportExcelForCS.ReadListFromStream(new ConsumptionPaymentForLocal(), workbook, false).Select(o => Pharos.Logic.Entity.BaseEntityExtension.InitEntity <ConsumptionPayment>(o))); } break; case "SysStoreUserInfo": list.AddRange(ExportExcelForCS.ReadListFromStream(new SysStoreUserInfoForLocal(), workbook, false).Select(o => Pharos.Logic.Entity.BaseEntityExtension.InitEntity <SysStoreUserInfo>(o))); break; case "MemberIntegral": list.AddRange(ExportExcelForCS.ReadListFromStream(new MemberIntegralForLocal(), workbook, false).Select(o => Pharos.Logic.Entity.BaseEntityExtension.InitEntity <MemberIntegral>(o))); break; default: break; } } catch (Exception ex) { throw new Exception(title + "," + ex.Message); } } foreach (var obj in list) { if (obj is SysStoreUserInfo) { var user = obj as SysStoreUserInfo; var u = BaseService <SysStoreUserInfo> .Find(o => o.UserCode == user.UserCode); if (u == null) { continue; } u.LoginDT = user.LoginDT; } else { Save(obj, false); } } if (list.Any()) { Save(list[0], true); msg = "导入成功"; } else { msg = "请选择导入文件"; } } } catch (Exception ex) { msg = ex.Message; new Sys.LogEngine().WriteError(ex); } return(msg); }
public void ForeignKeysTest() { using (var connection = SqlProvider.OpenConnection()) { connection.ExecuteNonQuery(@" CREATE TABLE [Numbers]( [ID] UNIQUEIDENTIFIER NOT NULL ROWGUIDCOL PRIMARY KEY DEFAULT(newid()), [Number] INTEGER NOT NULL, [Date] DATETIME NULL, [RowVersion] RowVersion );"); connection.ExecuteNonQuery(@" CREATE TABLE [Powers]( [ID] UNIQUEIDENTIFIER NOT NULL ROWGUIDCOL PRIMARY KEY DEFAULT(newid()), [Number] UNIQUEIDENTIFIER NULL REFERENCES Numbers(Id), [Exponent] INTEGER NOT NULL, [Value] INTEGER NOT NULL, [RowVersion] RowVersion );"); } try { var numbersSchema = new TableSchema("Numbers"); var powersSchema = new TableSchema("Powers"); numbersSchema.PrimaryKey = numbersSchema.Columns.AddValueColumn("ID", typeof(Guid), null); numbersSchema.Columns.AddValueColumn("Number", typeof(int), 0); numbersSchema.Columns.AddValueColumn("Date", typeof(DateTime?), null); powersSchema.PrimaryKey = powersSchema.Columns.AddValueColumn("ID", typeof(Guid), null); powersSchema.Columns.AddForeignKey("Number", numbersSchema, "Powers").AllowNulls = true; powersSchema.Columns.AddValueColumn("Exponent", typeof(int), 0); powersSchema.Columns.AddValueColumn("Value", typeof(int), 0); var context = new DataContext(); Table numbersTable, powersTable; context.Tables.AddTable(numbersTable = new Table(numbersSchema)); context.Tables.AddTable(powersTable = new Table(powersSchema)); var syncContext = new DataSyncContext(context, SqlProvider); syncContext.Tables.AddDefaultMappings(); Action verify = delegate { var newContext = new DataContext(); newContext.Tables.AddTable(new Table(numbersSchema)); newContext.Tables.AddTable(new Table(powersSchema)); var newSyncContext = new DataSyncContext(newContext, SqlProvider); newSyncContext.Tables.AddDefaultMappings(); newSyncContext.ReadData(); AssertTablesEqual(context.Tables[numbersSchema], newContext.Tables[numbersSchema]); AssertTablesEqual(context.Tables[powersSchema], newContext.Tables[powersSchema]); context.Tables[powersSchema].Rows.Clear(); context.Tables[numbersSchema].Rows.Clear(); syncContext.ReadData(); AssertTablesEqual(newContext.Tables[numbersSchema], context.Tables[numbersSchema]); AssertTablesEqual(newContext.Tables[powersSchema], context.Tables[powersSchema]); }; for (int i = 0; i < 10; i++) { var row = numbersTable.Rows.AddFromValues(Guid.NewGuid(), i); if (rand.NextDouble() < .4) { row["Date"] = DateTime.Today.AddMinutes((int)(1000000 * (.5 - rand.NextDouble()))); } for (int j = 0; j < 10; j++) { powersTable.Rows.AddFromValues(Guid.NewGuid(), row, j, (int)Math.Pow(i, j)); } powersTable.Rows.Remove(powersTable.Rows.Last()); } powersTable.Rows.AddFromValues(Guid.NewGuid(), null, 1, -1); powersTable.Rows.AddFromValues(Guid.NewGuid(), null, 2, -1); powersTable.Rows.AddFromValues(Guid.NewGuid(), null, 3, -1); powersTable.Rows.AddFromValues(Guid.NewGuid(), null, 4, -1); syncContext.WriteData(); verify(); for (int i = powersTable.Rows.Count - 1; i >= 0; i--) { if (rand.NextDouble() < .2) { powersTable.Rows.RemoveAt(i); } } for (int i = numbersTable.Rows.Count - 1; i >= 0; i--) { if (rand.NextDouble() < .2) { while (numbersTable.Rows[i].ChildRows("Powers").Count > 0) { if (rand.NextDouble() < .5) { numbersTable.Rows[i].ChildRows("Powers")[0].RemoveRow(); } else { numbersTable.Rows[i].ChildRows("Powers")[0]["Number"] = numbersTable.Rows[rand.Next(numbersTable.Rows.Count)]; } } numbersTable.Rows.RemoveAt(i); } } syncContext.WriteData(); verify(); var hundred = numbersTable.Rows.AddFromValues(Guid.NewGuid(), 100); powersTable.Rows.AddFromValues(Guid.NewGuid(), hundred, 1, 100); powersTable.Rows.AddFromValues(Guid.NewGuid(), hundred, 2, 10000); powersTable.Rows[rand.Next(powersTable.Rows.Count)]["Number"] = hundred; syncContext.WriteData(); verify(); } finally { using (var connection = SqlProvider.OpenConnection()) { connection.ExecuteNonQuery(@"DROP TABLE Powers;"); connection.ExecuteNonQuery(@"DROP TABLE Numbers;"); } } }
public IEnumerable <SynchronousDb> GetItems() { using (DataSyncContext context = new DataSyncContext()) { return(context.SynchronousDb.ToList()); } }
public void ForeignKeysTest() { using (var connection = SqlProvider.OpenConnection()) { connection.ExecuteNonQuery(@" CREATE TABLE [Numbers]( [ID] UNIQUEIDENTIFIER NOT NULL ROWGUIDCOL PRIMARY KEY DEFAULT(newid()), [Number] INTEGER NOT NULL, [Date] DATETIME NULL, [RowVersion] RowVersion );"); connection.ExecuteNonQuery(@" CREATE TABLE [Powers]( [ID] UNIQUEIDENTIFIER NOT NULL ROWGUIDCOL PRIMARY KEY DEFAULT(newid()), [Number] UNIQUEIDENTIFIER NULL REFERENCES Numbers(Id), [Exponent] INTEGER NOT NULL, [Value] INTEGER NOT NULL, [RowVersion] RowVersion );"); } try { var numbersSchema = new TableSchema("Numbers"); var powersSchema = new TableSchema("Powers"); numbersSchema.PrimaryKey = numbersSchema.Columns.AddValueColumn("ID", typeof(Guid), null); numbersSchema.Columns.AddValueColumn("Number", typeof(int), 0); numbersSchema.Columns.AddValueColumn("Date", typeof(DateTime?), null); powersSchema.PrimaryKey = powersSchema.Columns.AddValueColumn("ID", typeof(Guid), null); powersSchema.Columns.AddForeignKey("Number", numbersSchema, "Powers").AllowNulls = true; powersSchema.Columns.AddValueColumn("Exponent", typeof(int), 0); powersSchema.Columns.AddValueColumn("Value", typeof(int), 0); var context = new DataContext(); Table numbersTable, powersTable; context.Tables.AddTable(numbersTable = new Table(numbersSchema)); context.Tables.AddTable(powersTable = new Table(powersSchema)); var syncContext = new DataSyncContext(context, SqlProvider); syncContext.Tables.AddDefaultMappings(); Action verify = delegate { var newContext = new DataContext(); newContext.Tables.AddTable(new Table(numbersSchema)); newContext.Tables.AddTable(new Table(powersSchema)); var newSyncContext = new DataSyncContext(newContext, SqlProvider); newSyncContext.Tables.AddDefaultMappings(); newSyncContext.ReadData(); AssertTablesEqual(context.Tables[numbersSchema], newContext.Tables[numbersSchema]); AssertTablesEqual(context.Tables[powersSchema], newContext.Tables[powersSchema]); context.Tables[powersSchema].Rows.Clear(); context.Tables[numbersSchema].Rows.Clear(); syncContext.ReadData(); AssertTablesEqual(newContext.Tables[numbersSchema], context.Tables[numbersSchema]); AssertTablesEqual(newContext.Tables[powersSchema], context.Tables[powersSchema]); }; for (int i = 0; i < 10; i++) { var row = numbersTable.Rows.AddFromValues(Guid.NewGuid(), i); if (rand.NextDouble() < .4) row["Date"] = DateTime.Today.AddMinutes((int)(1000000 * (.5 - rand.NextDouble()))); for (int j = 0; j < 10; j++) { powersTable.Rows.AddFromValues(Guid.NewGuid(), row, j, (int)Math.Pow(i, j)); } powersTable.Rows.Remove(powersTable.Rows.Last()); } powersTable.Rows.AddFromValues(Guid.NewGuid(), null, 1, -1); powersTable.Rows.AddFromValues(Guid.NewGuid(), null, 2, -1); powersTable.Rows.AddFromValues(Guid.NewGuid(), null, 3, -1); powersTable.Rows.AddFromValues(Guid.NewGuid(), null, 4, -1); syncContext.WriteData(); verify(); for (int i = powersTable.Rows.Count - 1; i >= 0; i--) { if (rand.NextDouble() < .2) powersTable.Rows.RemoveAt(i); } for (int i = numbersTable.Rows.Count - 1; i >= 0; i--) { if (rand.NextDouble() < .2) { while (numbersTable.Rows[i].ChildRows("Powers").Count > 0) { if (rand.NextDouble() < .5) numbersTable.Rows[i].ChildRows("Powers")[0].RemoveRow(); else numbersTable.Rows[i].ChildRows("Powers")[0]["Number"] = numbersTable.Rows[rand.Next(numbersTable.Rows.Count)]; } numbersTable.Rows.RemoveAt(i); } } syncContext.WriteData(); verify(); var hundred = numbersTable.Rows.AddFromValues(Guid.NewGuid(), 100); powersTable.Rows.AddFromValues(Guid.NewGuid(), hundred, 1, 100); powersTable.Rows.AddFromValues(Guid.NewGuid(), hundred, 2, 10000); powersTable.Rows[rand.Next(powersTable.Rows.Count)]["Number"] = hundred; syncContext.WriteData(); verify(); } finally { using (var connection = SqlProvider.OpenConnection()) { connection.ExecuteNonQuery(@"DROP TABLE Powers;"); connection.ExecuteNonQuery(@"DROP TABLE Numbers;"); } } }
public SourceTable GetItemByID(int id) { using (DataSyncContext context = new DataSyncContext()) { return(context.SourceTables.Where(c => c.ID == id).FirstOrDefault()); } }
protected override DataSyncContext CreateDataContext() { var context = new DataContext(); //These columns cannot be added in the strongly-typed row //because the People table must be usable without pledges //or payments. (eg, ListMaker or Rafflizer) if (!Person.Schema.Columns.Contains("TotalPaid")) { //This can be called multiple times in the designer AppDomain Person.Schema.Columns.AddCalculatedColumn<Person, decimal>("TotalPaid", person => person.Payments.Sum(p => p.Amount)); Person.Schema.Columns.AddCalculatedColumn<Person, decimal>("TotalPledged", person => person.Pledges.Sum(p => p.Amount)); Person.Schema.Columns.AddCalculatedColumn<decimal>("BalanceDue", person => person.Field<decimal>("TotalPledged") - person.Field<decimal>("TotalPaid")); Pledge.Schema.Columns.AddCalculatedColumn<Pledge, decimal>("UnlinkedAmount", p => p.Amount <= 0 ? 0 : p.Amount - p.LinkedPayments.Sum(o => o.Amount)); } context.Tables.AddTable(PledgeLink.CreateTable()); context.Tables.AddTable(Payment.CreateTable()); context.Tables.AddTable(Pledge.CreateTable()); context.Tables.AddTable(EmailAddress.CreateTable()); context.Tables.AddTable(LoggedStatement.CreateTable()); context.Tables.AddTable(Person.CreateTable()); context.Tables.AddTable(Deposit.CreateTable()); context.Tables.AddTable(RelativeLink.CreateTable()); if (IsDesignTime) AddDesignTimeTables(context); var syncContext = new DataSyncContext(context, new SqlServerSqlProvider(DB.Default)); syncContext.Tables.AddPrimaryMappings(); return syncContext; }