public void ShouldBatchStatementsWhenSendingToSqlServer() { using (var trans = _context.Database.BeginTransaction()) { var prod1 = TestHelpers.CreateProduct("1"); _context.Add(prod1); var prod2 = TestHelpers.CreateProduct("2"); _context.Add(prod2); var prod3 = TestHelpers.CreateProduct("3"); _context.Add(prod3); //This will automatically create one statement with three inserts _context.SaveChanges(); trans.Rollback(); } }
public void test3() { var product1 = TestHelpers.CreateProduct("1"); _context.Add(product1); Assert.Equal(EntityState.Added, _context.Entry(product1).State); Assert.Single(_context.ChangeTracker.Entries()); }
public Core.Models.Product InsertProduct(Core.Models.Product product) { var addProduct = Factory.CreateProductEntity(product); AdventureWorksContext.Add(addProduct); AdventureWorksContext.SaveChanges(); return(Factory.CreateProductDTO(addProduct)); }
private static void Main() { using (var db = new AdventureWorksContext()) { db.Database.EnsureDeleted(); db.Database.EnsureCreated(); foreach (var accountNumber in GetAccountNumbers(2000)) { db.Add(new Customer { AccountNumber = accountNumber, }); } db.SaveChanges(); } // Warmup using (var db = new AdventureWorksContext()) { var customer = db.Customers.First(); } RunTest( accountNumbers => { using (var db = new AdventureWorksContext()) { foreach (var id in accountNumbers) { // Use a regular auto-compiled query var customer = db.Customers.Single(c => c.AccountNumber == id); } } }, name: "Regular"); RunTest( accountNumbers => { // Create an explicit compiled query var query = EF.CompileQuery( (AdventureWorksContext db, string id) => db.Customers.Single(c => c.AccountNumber == id)); using (var db = new AdventureWorksContext()) { foreach (var id in accountNumbers) { // Invoke the compiled query query(db, id); } } }, name: "Compiled"); }
public async Task <IActionResult> Create([Bind("ContactTypeId,Name,ModifiedDate")] ContactType contactType) { if (ModelState.IsValid) { _context.Add(contactType); await _context.SaveChangesAsync(); return(RedirectToAction(nameof(Index))); } return(View(contactType)); }
public async Task <IActionResult> Create([Bind("DatabaseLogId,PostTime,DatabaseUser,Event,Schema,Object,Tsql,XmlEvent")] DatabaseLog databaseLog) { if (ModelState.IsValid) { _context.Add(databaseLog); await _context.SaveChangesAsync(); return(RedirectToAction(nameof(Index))); } return(View(databaseLog)); }
public async Task <IActionResult> Create([Bind("BusinessEntityId,Rowguid,ModifiedDate")] BusinessEntity businessEntity) { if (ModelState.IsValid) { _context.Add(businessEntity); await _context.SaveChangesAsync(); return(RedirectToAction(nameof(Index))); } return(View(businessEntity)); }
public async Task <IActionResult> Create([Bind("CustomerId,NameStyle,Title,FirstName,MiddleName,LastName,Suffix,CompanyName,SalesPerson,EmailAddress,Phone,PasswordHash,PasswordSalt,Rowguid,ModifiedDate")] Customer customer) { if (ModelState.IsValid) { _context.Add(customer); await _context.SaveChangesAsync(); return(RedirectToAction(nameof(Index))); } return(View(customer)); }
public async Task <IActionResult> Create([Bind("DepartmentId,Name,GroupName,ModifiedDate")] Department department) { if (ModelState.IsValid) { _context.Add(department); await _context.SaveChangesAsync(); return(RedirectToAction(nameof(Index))); } return(View(department)); }
public async Task <IActionResult> Create([Bind("SystemInformationId,DatabaseVersion,VersionDate,ModifiedDate")] AwbuildVersion awbuildVersion) { if (ModelState.IsValid) { _context.Add(awbuildVersion); await _context.SaveChangesAsync(); return(RedirectToAction(nameof(Index))); } return(View(awbuildVersion)); }
public async Task <IActionResult> Create([Bind("CreditCardId,CardType,CardNumber,ExpMonth,ExpYear,ModifiedDate")] CreditCard creditCard) { if (ModelState.IsValid) { _context.Add(creditCard); await _context.SaveChangesAsync(); return(RedirectToAction(nameof(Index))); } return(View(creditCard)); }
public async Task <IActionResult> Create([Bind("AddressId,AddressLine1,AddressLine2,City,StateProvinceId,PostalCode,Rowguid,ModifiedDate")] Address address) { if (ModelState.IsValid) { _context.Add(address); await _context.SaveChangesAsync(); return(RedirectToAction(nameof(Index))); } ViewData["StateProvinceId"] = new SelectList(_context.StateProvince, "StateProvinceId", "CountryRegionCode", address.StateProvinceId); return(View(address)); }
public async Task <IActionResult> Create([Bind("TerritoryId,Name,CountryRegionCode,Group,SalesYtd,SalesLastYear,CostYtd,CostLastYear,Rowguid,ModifiedDate")] SalesTerritory salesTerritory) { if (ModelState.IsValid) { _context.Add(salesTerritory); await _context.SaveChangesAsync(); return(RedirectToAction(nameof(Index))); } ViewData["CountryRegionCode"] = new SelectList(_context.CountryRegion, "CountryRegionCode", "CountryRegionCode", salesTerritory.CountryRegionCode); return(View(salesTerritory)); }
public async Task <IActionResult> Create([Bind("BusinessEntityId,NationalIdnumber,LoginId,OrganizationLevel,JobTitle,BirthDate,MaritalStatus,Gender,HireDate,SalariedFlag,VacationHours,SickLeaveHours,CurrentFlag,Rowguid,ModifiedDate")] Employee employee) { if (ModelState.IsValid) { _context.Add(employee); await _context.SaveChangesAsync(); return(RedirectToAction(nameof(Index))); } ViewData["BusinessEntityId"] = new SelectList(_context.People, "BusinessEntityId", "FirstName", employee.BusinessEntityId); return(View(employee)); }
public async Task <IActionResult> Create([Bind("StateProvinceId,StateProvinceCode,CountryRegionCode,IsOnlyStateProvinceFlag,Name,TerritoryId,Rowguid,ModifiedDate")] StateProvince stateProvince) { if (ModelState.IsValid) { _context.Add(stateProvince); await _context.SaveChangesAsync(); return(RedirectToAction(nameof(Index))); } ViewData["CountryRegionCode"] = new SelectList(_context.CountryRegion, "CountryRegionCode", "CountryRegionCode", stateProvince.CountryRegionCode); ViewData["TerritoryId"] = new SelectList(_context.SalesTerritory, "TerritoryId", "CountryRegionCode", stateProvince.TerritoryId); return(View(stateProvince)); }
public async Task <IActionResult> Create([Bind("CountryRegionCode,CurrencyCode,ModifiedDate")] CountryRegionCurrency countryRegionCurrency) { if (ModelState.IsValid) { _context.Add(countryRegionCurrency); await _context.SaveChangesAsync(); return(RedirectToAction(nameof(Index))); } ViewData["CountryRegionCode"] = new SelectList(_context.CountryRegion, "CountryRegionCode", "CountryRegionCode", countryRegionCurrency.CountryRegionCode); ViewData["CurrencyCode"] = new SelectList(_context.Currency, "CurrencyCode", "CurrencyCode", countryRegionCurrency.CurrencyCode); return(View(countryRegionCurrency)); }
public async Task <IActionResult> Create([Bind("CurrencyRateId,CurrencyRateDate,FromCurrencyCode,ToCurrencyCode,AverageRate,EndOfDayRate,ModifiedDate")] CurrencyRate currencyRate) { if (ModelState.IsValid) { _context.Add(currencyRate); await _context.SaveChangesAsync(); return(RedirectToAction(nameof(Index))); } ViewData["FromCurrencyCode"] = new SelectList(_context.Currency, "CurrencyCode", "CurrencyCode", currencyRate.FromCurrencyCode); ViewData["ToCurrencyCode"] = new SelectList(_context.Currency, "CurrencyCode", "CurrencyCode", currencyRate.ToCurrencyCode); return(View(currencyRate)); }
public async Task <IActionResult> Create([Bind("CustomerId,PersonId,StoreId,TerritoryId,AccountNumber,Rowguid,ModifiedDate")] Customer customer) { if (ModelState.IsValid) { _context.Add(customer); await _context.SaveChangesAsync(); return(RedirectToAction(nameof(Index))); } ViewData["PersonId"] = new SelectList(_context.Person, "BusinessEntityId", "FirstName", customer.PersonId); ViewData["StoreId"] = new SelectList(_context.Store, "BusinessEntityId", "Name", customer.StoreId); ViewData["TerritoryId"] = new SelectList(_context.SalesTerritory, "TerritoryId", "CountryRegionCode", customer.TerritoryId); return(View(customer)); }
public async Task <IActionResult> Create([Bind("BusinessEntityId,PersonId,ContactTypeId,Rowguid,ModifiedDate")] BusinessEntityContact businessEntityContact) { if (ModelState.IsValid) { _context.Add(businessEntityContact); await _context.SaveChangesAsync(); return(RedirectToAction(nameof(Index))); } ViewData["BusinessEntityId"] = new SelectList(_context.BusinessEntity, "BusinessEntityId", "BusinessEntityId", businessEntityContact.BusinessEntityId); ViewData["ContactTypeId"] = new SelectList(_context.ContactType, "ContactTypeId", "Name", businessEntityContact.ContactTypeId); ViewData["PersonId"] = new SelectList(_context.Person, "BusinessEntityId", "FirstName", businessEntityContact.PersonId); return(View(businessEntityContact)); }
public async Task <IActionResult> Create([Bind("BillOfMaterialsId,ProductAssemblyId,ComponentId,StartDate,EndDate,UnitMeasureCode,Bomlevel,PerAssemblyQty,ModifiedDate")] BillOfMaterials billOfMaterials) { if (ModelState.IsValid) { _context.Add(billOfMaterials); await _context.SaveChangesAsync(); return(RedirectToAction(nameof(Index))); } ViewData["ComponentId"] = new SelectList(_context.Product, "ProductId", "Name", billOfMaterials.ComponentId); ViewData["ProductAssemblyId"] = new SelectList(_context.Product, "ProductId", "Name", billOfMaterials.ProductAssemblyId); ViewData["UnitMeasureCode"] = new SelectList(_context.UnitMeasure, "UnitMeasureCode", "UnitMeasureCode", billOfMaterials.UnitMeasureCode); return(View(billOfMaterials)); }
public async Task <IActionResult> Create([Bind("BusinessEntityId,AddressId,AddressTypeId,Rowguid,ModifiedDate")] BusinessEntityAddress businessEntityAddress) { if (ModelState.IsValid) { _context.Add(businessEntityAddress); await _context.SaveChangesAsync(); return(RedirectToAction(nameof(Index))); } ViewData["AddressId"] = new SelectList(_context.Address, "AddressId", "AddressLine1", businessEntityAddress.AddressId); ViewData["AddressTypeId"] = new SelectList(_context.AddressType, "AddressTypeId", "Name", businessEntityAddress.AddressTypeId); ViewData["BusinessEntityId"] = new SelectList(_context.BusinessEntity, "BusinessEntityId", "BusinessEntityId", businessEntityAddress.BusinessEntityId); return(View(businessEntityAddress)); }
public void ShouldTrackAddedRecords() { var product1 = TestHelpers.CreateProduct("1"); _context.Product.Add(product1); Assert.Equal(EntityState.Added, _context.Entry(product1).State); Assert.Single(_context.ChangeTracker.Entries()); //this shows that you can add directly to the context if you want var product2 = TestHelpers.CreateProduct("2"); _context.Add(product2); Assert.Equal(EntityState.Added, _context.Entry(product1).State); Assert.Equal(2, _context.ChangeTracker.Entries().Count()); }
public async Task <IActionResult> Create([Bind("ProductId,Name,ProductNumber,MakeFlag,FinishedGoodsFlag,Color,SafetyStockLevel,ReorderPoint,StandardCost,ListPrice,Size,SizeUnitMeasureCode,WeightUnitMeasureCode,Weight,DaysToManufacture,ProductLine,Class,Style,ProductSubcategoryId,ProductModelId,SellStartDate,SellEndDate,DiscontinuedDate,Rowguid,ModifiedDate")] Product product) { if (ModelState.IsValid) { _context.Add(product); await _context.SaveChangesAsync(); return(RedirectToAction(nameof(Index))); } ViewData["ProductModelId"] = new SelectList(_context.ProductModels, "ProductModelId", "Name", product.ProductModelId); ViewData["ProductSubcategoryId"] = new SelectList(_context.ProductSubcategories, "ProductSubcategoryId", "Name", product.ProductSubcategoryId); ViewData["SizeUnitMeasureCode"] = new SelectList(_context.UnitMeasures, "UnitMeasureCode", "UnitMeasureCode", product.SizeUnitMeasureCode); ViewData["WeightUnitMeasureCode"] = new SelectList(_context.UnitMeasures, "UnitMeasureCode", "UnitMeasureCode", product.WeightUnitMeasureCode); return(View(product)); }
public void ShouldDeleteEntityUsingState() { using (var transaction = _context.Database.BeginTransaction()) { //Arrange the test var product = TestHelpers.CreateProduct("1"); _context.Add(product); _context.SaveChanges(); var productId = product.ProductId; Assert.Equal(1, _context.Product.Count(p => p.ProductId == productId)); _context.Entry(product).State = EntityState.Detached; //Act _context.Entry(product).State = EntityState.Deleted; _context.SaveChanges(); //Assert Assert.Equal(0, _context.Product.Count(p => p.ProductId == productId)); transaction.Rollback(); } }
public virtual async Task Scenario_ConflictResolution_From_Client_Side() { // ------------------------------------------------------- // Setup the conflict // ------------------------------------------------------- // create a server schema with seeding await this.EnsureDatabaseSchemaAndSeedAsync(this.Server, false, UseFallbackSchema); var clientDatabaseName = HelperDatabase.GetRandomName(); var clientProvider = new SqliteSyncProvider($"{clientDatabaseName}.db"); var client = (clientDatabaseName, ProviderType.Sqlite, Provider : clientProvider); // create a simple setup with one table to sync var productCategoryTableName = this.Server.ProviderType == ProviderType.Sql ? "SalesLT.ProductCategory" : "ProductCategory"; var setup = new SyncSetup(productCategoryTableName); // even if it's default value, let's set the default conflict resolutio var options = new SyncOptions { ConflictResolutionPolicy = ConflictResolutionPolicy.ServerWins }; // configure kestrell and run this.Kestrell.AddSyncServer(this.Server.Provider.GetType(), this.Server.Provider.ConnectionString, SyncOptions.DefaultScopeName, setup, options); var serviceUri = this.Kestrell.Run(); // Execute a sync on to have the databases in sync var agent = new SyncAgent(clientProvider, new WebRemoteOrchestrator(serviceUri), options); var r = await agent.SynchronizeAsync(); // Conflict product category var conflictProductCategoryId = HelperDatabase.GetRandomName().ToUpperInvariant().Substring(0, 6); var productCategoryNameClient = "CLI BIKES " + HelperDatabase.GetRandomName(); var productCategoryNameServer = "SRV BIKES " + HelperDatabase.GetRandomName(); // Insert line on server and sync to have it on the client as well using (var ctx = new AdventureWorksContext(this.Server)) { ctx.Add(new ProductCategory { ProductCategoryId = conflictProductCategoryId, Name = "BIKES" }); await ctx.SaveChangesAsync(); } // Execute a sync on all clients to initialize client and server schema await agent.SynchronizeAsync(); // Update each client to generate an update conflict using (var ctx = new AdventureWorksContext(client, this.UseFallbackSchema)) { var pc = ctx.ProductCategory.Find(conflictProductCategoryId); pc.Name = productCategoryNameClient; await ctx.SaveChangesAsync(); } // Update server using (var ctx = new AdventureWorksContext(this.Server)) { var pc = ctx.ProductCategory.Find(conflictProductCategoryId); pc.Name = productCategoryNameServer; await ctx.SaveChangesAsync(); } await this.Kestrell.StopAsync(); // ------------------------------------------------------- // From that point, we know we have a conflict // ------------------------------------------------------- // Let's configure the server side // Configure kestrell this.Kestrell.AddSyncServer(this.Server.Provider.GetType(), this.Server.Provider.ConnectionString, SyncOptions.DefaultScopeName, setup, options); // Create server web proxy var serverHandler = new RequestDelegate(async context => { var webServerAgent = context.RequestServices.GetService(typeof(WebServerAgent)) as WebServerAgent; webServerAgent.RemoteOrchestrator.OnApplyChangesFailed(async acf => { // Check conflict is correctly set var localRow = acf.Conflict.LocalRow; var remoteRow = acf.Conflict.RemoteRow; // remote is client; local is server Assert.StartsWith("CLI", remoteRow["Name"].ToString()); Assert.StartsWith("SRV", localRow["Name"].ToString()); Assert.Equal(ConflictResolution.ServerWins, acf.Resolution); Assert.Equal(ConflictType.RemoteExistsLocalExists, acf.Conflict.Type); }); await webServerAgent.HandleRequestAsync(context); }); serviceUri = this.Kestrell.Run(serverHandler); // get a new agent (since service uri has changed) agent = new SyncAgent(clientProvider, new WebRemoteOrchestrator(serviceUri), options); // From client : Remote is server, Local is client // From here, we are going to let the client decides // who is the winner of the conflict : agent.LocalOrchestrator.OnApplyChangesFailed(acf => { // Check conflict is correctly set var localRow = acf.Conflict.LocalRow; var remoteRow = acf.Conflict.RemoteRow; // From that point, you can easily letting the client decides // who is the winner // Show a UI with the local / remote row and // letting him decides what is the good row version // for testing purpose; will just going to set name to some fancy BLA BLA value // SHOW UI // OH.... CLIENT DECIDED TO SET NAME TO "BLA BLA BLA" // BE AS FAST AS POSSIBLE IN YOUR DESICION, // SINCE WE HAVE AN OPENED CONNECTION / TRANSACTION RUNNING remoteRow["Name"] = "HHH" + HelperDatabase.GetRandomName(); // Mandatory to override the winner registered in the tracking table // Use with caution ! // To be sure the row will be marked as updated locally, // the scope id should be set to null acf.SenderScopeId = null; }); // First sync, we allow server to resolve the conflict and send back the result to client var s = await agent.SynchronizeAsync(); Assert.Equal(1, s.TotalChangesDownloaded); Assert.Equal(1, s.TotalChangesUploaded); Assert.Equal(1, s.TotalResolvedConflicts); // From this point the Server row Name is STILL "SRV...." // And the Client row NAME is "BLA BLA BLA..." // Make a new sync to send "BLA BLA BLA..." to Server s = await agent.SynchronizeAsync(); Assert.Equal(0, s.TotalChangesDownloaded); Assert.Equal(1, s.TotalChangesUploaded); Assert.Equal(0, s.TotalResolvedConflicts); await CheckProductCategoryRowsAsync(client, "HHH"); }
public int Add(ProductCategory productCategory) { _context.Add(productCategory); return(_context.SaveChanges()); }