public async Task Delete(MeasurePointBase point, Action onSuccess = null, Action <Exception> onException = null) { await Task.Factory.StartNew(() => { using (var repo = new EntityRepository <MeasurePointBase>(_connection)) { if (point is FloutecMeasureLine) { var line = repo.GetAll() .Where(e => e.Id == point.Id) .OfType <FloutecMeasureLine>() .Include(l => l.AlarmData) .Include(l => l.HourlyData) .Include(l => l.IdentData) .Include(l => l.InstantData) .Include(l => l.InterData) .Single(); repo.Delete(new List <FloutecMeasureLine> { line }); } if (point is Roc809MeasurePoint) { var line = repo.GetAll() .Where(e => e.Id == point.Id) .OfType <Roc809MeasurePoint>() .Include(l => l.DailyData) .Include(l => l.MinuteData) .Include(l => l.PeriodicData) .Single(); repo.Delete(new List <Roc809MeasurePoint> { line }); } } }, TaskCreationOptions.LongRunning) .ContinueWith(result => { if (result.Exception != null) { onException?.Invoke(result.Exception.InnerException); } else { onSuccess?.Invoke(); } }, TaskScheduler.FromCurrentSynchronizationContext()); }
/// <summary> /// Удаление песни /// </summary> /// <param name="chordTabId"></param> /// <returns></returns> public ViewResult DeleteAnnoun(string chordTabId) { IRepository <User> users = new EntityRepository <User>(SingletonSession.getInstance().sess); User user = users.ReadById(Int32.Parse(HttpContext.Session.GetString("userid"))); foreach (ChordTab a in user._ChordTab) { if (a.UID == Int32.Parse(chordTabId)) { user._ChordTab.Remove(a); a._User = null; foreach (Photos p in a._Photos) { string path = hosting.WebRootPath + "/images/" + p.Name; if (System.IO.File.Exists(path)) { System.IO.File.Delete(path); } } using (ITransaction transaction = SingletonSession.getInstance().sess.BeginTransaction()) { IRepository <ChordTab> chordTabs = new EntityRepository <ChordTab>(SingletonSession.getInstance().sess); chordTabs.Delete(a); transaction.Commit(); } break; } } return(PersonalPage()); }
public async Task Delete(int scanId, Action onSuccess = null, Action <Exception> onException = null) { await Task.Factory.StartNew(() => { using (var repo = new EntityRepository <PeriodicScan>(_connection)) { var sc = repo.GetAll() .Where(s => s.Id == scanId) .Include(s => s.Members) .Single(); repo.Delete(new List <PeriodicScan> { sc }); } }, TaskCreationOptions.LongRunning) .ContinueWith(result => { if (result.Exception != null) { onException?.Invoke(result.Exception.InnerException); } else { onSuccess?.Invoke(); } }, TaskScheduler.FromCurrentSynchronizationContext()); }
public async Task <IHttpActionResult> DeleteLocation(int id) { Location dbObject = await locationDB.GetSingleOrDefaultWhere(o => o.ID == id); if (dbObject == null) { return(NotFound()); } else { Task <List <Item> > itemlist = itemDB.GetAllWhere(o => o.LocationID == id); foreach (var Item in itemlist.Result) { Item.LocationID = null; } await itemDB.Save(); locationDB.Delete(dbObject); await locationDB.Save(); return(StatusCode(HttpStatusCode.NoContent)); } }
public void TestDeletedItems() { T entity1 = CreateNewAndDetach(); T entity2 = CreateNewAndDetach(); entity1 = EntityRepository <T> .Get(entity1.ObjectId); entity2 = EntityRepository <T> .Get(entity2.ObjectId); With.Transaction(delegate { EntityRepository <T> .Delete(entity1); EntityRepository <T> .Delete(entity2); } ); ICollection <T> deletedEntities = EntityRepository <T> .DeletedItems; Assert.AreEqual(deletedEntities.Count, 2, "Deleted Items incorrect"); foreach (T entity in deletedEntities) { Assert.IsTrue((entity1.Id.Equals(entity.Id) || (entity2.Id.Equals(entity.Id)))); } }
public virtual void Delete(int id) { var domainModel = Find(id); _listOfTTypeDeleted.Add(domainModel); EventAggregator.Publish(this, new EntityDeletingArgs <T>(domainModel)); EntityRepository.Delete(id); }
public void EntityRemove <TEntity>(int id, IEntity entity) where TEntity : IEntity { ApplicationPlatformContext <TEntity> ContextEntity = new ApplicationPlatformContext <TEntity>(); ContextEntity.Initialized(); EntityRepository <TEntity> repository = new EntityRepository <TEntity>(ContextEntity, entity, false); repository.Delete(id); }
public void TestDeleteDeletedCandidate() { TestCandidate candidate = CreateSaveAndSoftDelete(); With.Transaction(delegate { EntityRepository <TestCandidate> .Delete(candidate); }); }
public void TestDeleteContact() { var currentTestContactRepository = new EntityRepository <Contact>("Contact"); var contactGuid = currentTestContactRepository.Create(new Contact()); currentTestContactRepository.Delete(contactGuid); Assert.AreEqual(0, currentTestContactRepository.All.Count()); }
protected override void OnExecute() { U entity = EntityRepository <U> .Get(_id); entity.ModifiedBy = UserId; entity.ModifiedOn = DateTime.Now; EntityRepository <U> .Delete(entity); base.OnExecute(); }
public bool Delete(long userId, Entity toDelete) { using (var tran = new TransactionScope()) { var toRet = _repository.Delete(toDelete); BlLog.Log(userId, Module, "Delete entity", "EntityDeleted", new object[] { toDelete.Pin }); tran.Complete(); return(toRet); } }
public void Delete_SessionReadOnly_ExceptionThrown() { var session = new Mock <ISession>(); session.Setup(x => x.DefaultReadOnly) .Returns(true); var repository = new EntityRepository <TestEntity>(session.Object); var entity = new TestEntity(); Assert.Throws <EntityRepositoryException>(() => repository.Delete(entity), "The Repository is read-only"); }
/// <summary> /// Deletes an entity and saves changings /// </summary> /// <param name="entity">An instance of entity</param> /// <returns>Return true if deletes successfully, else false</returns> public virtual bool Delete(int id) { var employee = _repository.GetSingle(id); if (employee == null) { return(false); } _repository.Delete(employee); return(_repository.Commit()); }
/// <summary> /// clear all my ratings, fav, like, /// </summary> /// <param name="userId"></param> /// <param name="targetId"></param> public virtual void ClearMyLRF(Guid userId, Guid targetId, LRFType type) { Dictionary <string, object> queryDict = new Dictionary <string, object>(); queryDict.Add("OwnerId", userId); queryDict.Add("TargetId", targetId); queryDict.Add("Type", type); var query = getNewQueryObject(); query.AppendQuery(queryDict, QueryLogic.And); EntityRepository.Delete(query); }
protected T CreateAndSoftDelete() { T entity = CreateNewAndDetach(); entity = EntityRepository <T> .Get(entity.ObjectId); With.Transaction(delegate { EntityRepository <T> .Delete(entity); } ); return(entity); }
public async Task <IHttpActionResult> DeleteItem(int id) { Item dbObject = await itemDB.GetSingleOrDefaultWhere(o => o.ID == id); if (dbObject == null) { return(NotFound()); } itemDB.Delete(dbObject); await itemDB.Save(); return(StatusCode(HttpStatusCode.NoContent)); }
public override bool Delete <TDto>(TDto dto) { TEntity primaryEntity = null; if (dto is IPrimary <TKey> ) { var id = (dto as IPrimary <TKey>).Id; primaryEntity = EntityRepository.GetById(id); } var entity = Mapper.Map(dto, primaryEntity); return(EntityRepository.Delete(entity)); }
private TestCandidate CreateSaveAndSoftDelete() { TestCandidate candidate = new TestCandidate(); candidate.Name = "Mohan"; Save(candidate); With.Transaction(delegate { EntityRepository <TestCandidate> .Delete(candidate); }); return(candidate); }
public static void Test() { // --------------------------------------------------------------------------------------------------- // If you want to build a DB Context from an existing database: // Install-Package Microsoft.EntityFrameworkCore.Tools // Sqlite: Scaffold-DbContext "DataSource=test.db" Microsoft.EntityFrameworkCore.Sqlite -OutputDir "NewFolder" // Postgre: Scaffold-DbContext "User ID=postgres;Password=secret;Server=localhost;Port=5432;Database=test;Integrated Security = true;Pooling = true" Npgsql.EntityFrameworkCore.PostgreSQL -OutputDir "NewFolder" // --------------------------------------------------------------------------------------------------- /* Option 1 - Pass options using builder * var optBuilder = new DbContextOptionsBuilder<testContext>(); * optBuilder.UseSqlite("DataSource=test.db"); * var dbCtxFactory = new DbContextFactory<testContext>(optBuilder.Options);*/ // Option 2 - Pass connection string //var dbCtxFactory = new DbContextFactory<testContext>(DatabaseEnums.POSTGRESQL, "User ID=postgres;Password=secret;Server=localhost;Port=5432;Database=test;Integrated Security = true;Pooling = true"); var dbCtxFactory = new DbContextFactory <testContext>(DatabaseEnums.SQLITE, "DataSource=test.db"); //IEntityStore<Person> personStore = new AuditableRepository<Person>(dbCtxFactory, httpContextAccessor: null); // Entity repository does physical delete and also does not have audit fields (updatedby, deletedon, ..) IEntityStore <Person> personStore = new EntityRepository <Person>(dbCtxFactory); // This factory and store can be moved to dependency injectors var me = new Person { Age = 30 }; personStore.SaveOrUpdate(me); var notClone = personStore.Get(me.Id); notClone.Age = 18; personStore.SaveOrUpdate(notClone); try { me.Age = 17; personStore.SaveOrUpdate(me); } catch (StaleDataException e) { // Message explains a more recent item exists (bigger Version number) so updating might lose data Console.WriteLine(e.Message); } personStore.Delete(notClone); personStore.DeleteAll(); }
public override async Task Update(ScheduledScan scan, Action onSuccess = null, Action <Exception> onException = null) { await Task.Factory.StartNew(() => { using (var scansRepo = new EntityRepository <ScheduledScan>(_connection)) { var existingScan = scansRepo.GetAll().Where(s => s.Id == scan.Id).Include(s => s.Periods).Single(); var periodsToDelete = existingScan.Periods.Where(ep => !scan.Periods.Select(p => p.Id).Contains(ep.Id)).ToList(); var periodsToAdd = scan.Periods.Where(p => p.Scan == null).ToList(); if (periodsToDelete.Any()) { using (var periodsRepo = new EntityRepository <ScanPeriod>(_connection)) { periodsToDelete.ForEach(s => { periodsRepo.Delete(s.Id); }); } } periodsToAdd.ForEach(s => { s.ScanId = existingScan.Id; s.Scan = existingScan; existingScan.Periods.Add(s); }); existingScan.DateModified = DateTime.Now; existingScan.Title = scan.Title; existingScan.IsActive = scan.IsActive; scansRepo.Update(existingScan); } }, TaskCreationOptions.LongRunning) .ContinueWith(result => { if (result.Exception != null) { onException?.Invoke(result.Exception.InnerException); } else { onSuccess?.Invoke(); } }, TaskScheduler.FromCurrentSynchronizationContext()); }
public void TestDelete() { using (var repo = new EntityRepository(new DatabaseContext(_options))) { var pen = new Entity() { Name = "Name" }; repo.Insert(pen); repo.Delete(1); } using (var repo = new EntityRepository(new DatabaseContext(_options))) { Assert.AreEqual(0, repo.Count()); } }
protected virtual bool Delete(T obj) { try { objRepository.Delete(obj); return(true); } catch (Exception ex) { LogException(ex, typeof(T).Name + " - " + "GTS.Clock.Business-Nhibernate Action"); throw ex; } finally { } }
public virtual void Delete(int id) { try { Authorize(Can_Delete); EntityRepository <T> .Delete(EntityRepository <T> .Get(id)); } catch (System.Exception ex) { bool reThrow = ExceptionHandler.HandleBusinessLogicLayerException(ex); if (reThrow) { throw; } } }
public void Delete_ItemById_ReturnsSingleRowDeleted() { var repositoryProvider = new Mock <IRepositoryProvider>(); var definitionProvider = new DataAnnotationsDefinitionProvider(); repositoryProvider.Setup(provider => provider.EntityDefinitionProvider).Returns(definitionProvider); repositoryProvider.Setup(provider => provider.Delete(It.IsAny <IEntitySet>())).Returns(1); int actual; using (var provider = repositoryProvider.Object) { var repository = new EntityRepository <ComplexEntity, ComplexRaisedRow>(provider, this.mapper); actual = repository.Delete(14); } Assert.AreEqual(1, actual); }
/// <summary> /// حذف یک آیتم /// </summary> /// <param name="shiftId"></param> /// <returns></returns> public bool DeleteShiftPair(decimal shiftPairId) { ShiftPair shiftPair = new ShiftPair() { ID = shiftPairId }; try { pairRep.Delete(shiftPair); return(true); } catch (Exception ex) { LogException(ex, "Shift", "DeleteShiftPair"); throw ex; } finally { } }
public void Should_delete_person_id_record_for_repository() { var person = new PersonEntity(); person.SetId(16); person.FirstName = "Red"; person.LastName = "Bull"; person.IsAwesome = true; var mockContext = new Mock <IRepositoryContext>(); mockContext.Setup(x => x.Query <PersonEntity>(It.IsAny <string>())).Returns(new List <PersonEntity>() { person }); mockContext.Setup(x => x.Execute(It.IsAny <string>())); var repository = new EntityRepository <PersonEntity>(mockContext.Object); var query = QueryOver.Of <PersonEntity>() .Where(x => x.PersonId == 16); var result = repository.Find(query).FirstOrDefault(); Assert.True(result.PersonId == person.PersonId); Assert.True(result.FirstName == person.FirstName); Assert.True(result.LastName == person.LastName); Assert.True(result.IsAwesome == person.IsAwesome); //not deleted yet Assert.True(result.IsDeleted == false); //call to delete repository.Delete(result); //flagged as deleted... yay!!! Assert.True(result.IsDeleted == true); mockContext.Verify(x => x.Query <PersonEntity>(It.IsAny <string>()), Times.Once); mockContext.Verify(x => x.Execute(It.IsAny <string>()), Times.Once); }
public async Task Delete(int scanId, Action onSuccess = null, Action <Exception> onException = null) { await Task.Factory.StartNew(() => { using (var repo = new EntityRepository <ScanMemberBase>(_connection)) { repo.Delete(scanId); } }, TaskCreationOptions.LongRunning) .ContinueWith(result => { if (result.Exception != null) { onException?.Invoke(result.Exception.InnerException); } else { onSuccess?.Invoke(); } }, TaskScheduler.FromCurrentSynchronizationContext()); }
public async Task Delete(int groupId, Action onSuccess = null, Action <Exception> onException = null) { await Task.Factory.StartNew(() => { using (var repo = new EntityRepository <EstimatorsGroup>(_connection)) { var group = repo.Get(groupId); group.Estimators.ToList().ForEach(e => e.Group = null); repo.Delete(groupId); } }, TaskCreationOptions.LongRunning) .ContinueWith(result => { if (result.Exception != null) { onException?.Invoke(result.Exception.InnerException); } else { onSuccess?.Invoke(); } }, TaskScheduler.FromCurrentSynchronizationContext()); }
private void btnDelete_Click(object sender, System.EventArgs e) { try { if (EntityRepository.VerificaVinculoProduto_Pedido(_entidade.Id)) { MessageBox.Show("Esse regiso possui vínculo com Produto ou Produto, não pode ser excluído!", "Aviso", MessageBoxButtons.OK); return; } var result = MessageBox.Show("Deseja excluir esse Registro? ", "Exclusão", MessageBoxButtons.YesNo, MessageBoxIcon.Question); if (result == DialogResult.Yes) { EntityRepository.Delete(_entidade); } MessageBox.Show("Registro excluído com sucesso!", "Sucesso", MessageBoxButtons.OK); this.Close(); } catch (Exception ex) { MessageBox.Show(ex.Message, "Erro", MessageBoxButtons.OK); } }
public void TestUnDelete() { T createdentity = CreateNew(); int id = createdentity.ObjectId; T entity = EntityRepository <T> .Get(id); With.Transaction(delegate { EntityRepository <T> .Delete(entity); } ); With.Transaction(delegate { EntityRepository <T> .UnDelete(entity); } ); T entityAfterUnDeletion = EntityRepository <T> .Get(id); Assert.IsNotNull(entityAfterUnDeletion, "UnDeletion did not work"); Assert.AreEqual(id, entityAfterUnDeletion.ObjectId, "After Undelete, Ids mismatch"); }
public void Test_EntityRepo_Delete() { var dbService = new TestDatabaseService(); var repository = new EntityRepository(dms, dbService, new SequenceProvider(dbService)); bool ex = false; using (var ctx = dbService.GetDatabaseContext(true)) { #region prepare data var jordan = new Author() { FirstName = "Robert", LastName = "Jordan", IsAlive = false, Born = new DateTime(1948, 10, 17), Rating = 10.0m }; var feist = new Author() { FirstName = "Raymond", LastName = "Feist", IsAlive = true, Born = new DateTime(1963, 2, 14), Rating = 6.7m }; var fb1 = new Book() { Title = "The Apprentice", Price = 19.90m }; var fb2 = new Book() { Title = "The Magician", Price = 17.10m }; //var jb1 = new Book() //{ // Title = "The Wheel of Time", // Price = 21.0m //}; repository.Create(jordan); repository.Create(feist); repository.Create(fb1); repository.Create(fb2); //repository.Create(jb1); repository.Attach(feist, new Relation("author", fb1)); repository.Attach(feist, new Relation("author", fb2)); //repository.Attach(jordan, new Relation("author", jb1)); #endregion var r1 = new EntityQuery2("author", jordan.Id); Assert.IsNotNull(repository.Read(r1)); repository.Delete(jordan); Assert.IsNull(repository.Read(r1)); var r2 = new EntityQuery2("author", feist.Id); Assert.IsNotNull(repository.Read(r2)); try { repository.Delete(feist); } catch (Exception) { ex = true; } } Assert.IsTrue(ex, "Exception not thrown when deleting author with attached relations"); }
//[TestMethod] public void Test_EntityRepo_Perf() { var r = new Random(); var dbService = new TestDatabaseService(); var repository = new EntityRepository(dms, dbService, new SequenceProvider(dbService)); using (var ctx = dbService.GetDatabaseContext(true)) { for (int i = 0; i < 1000; i++) { EntityUpdate update = new EntityUpdate("author"); update.Set("firstname", "Robert" + i); update.Set("lastname", "Jordan"); update.Set("isalive", false); update.Set("Born", new DateTime(1948, 10, 17)); update.Set("Rating", 5.5m + r.Next(4)); var id = repository.Create(update.ToEntity()); Assert.IsTrue(id > 0); EntityQuery2 q = new EntityQuery2("author", id); q.AddProperties("FirstName", "lastname", "isalive", "born", "rating"); var e = repository.Read(q); foreach (var pu in update.PropertyUpdates) { Assert.AreEqual(pu.Value, e.Data[pu.Key]); } EntityUpdate update2 = new EntityUpdate(e.Name, e.Id); update2.Set("rating", 5.5m + r.Next(4)); update2.Set("lastname", e.Data["lastname"] + "_EDIT"); repository.Update(update2.ToEntity()); e = repository.Read(q); foreach (var pu in update2.PropertyUpdates) { Assert.AreEqual(pu.Value, e.Data[pu.Key]); } foreach (var pu in update.PropertyUpdates) { if (!pu.Key.Equals("rating", StringComparison.InvariantCultureIgnoreCase) && !pu.Key.Equals("lastname", StringComparison.InvariantCultureIgnoreCase)) Assert.AreEqual(pu.Value, e.Data[pu.Key]); } } ctx.Complete(); } using (var ctx = dbService.GetDatabaseContext(true)) { var qAll = new EntityQuery2("Author"); var all = repository.Search(qAll); Assert.AreEqual(1000, all.Count()); foreach (var a in all) repository.Delete(a); Assert.AreEqual(0, repository.Search(qAll).Count()); } }
public void Test_EntityOperation_Update() { var dbService = new TestDatabaseService(); var repo = new EntityRepository(dms, dbService, new SequenceProvider(dbService)); IEntityOperationService svc = new EntityOperationService(repo, dbService, new IEntityOperationInspector[] { new Inspector() }, new IEntityQueryInspector[] { new Inspector() }, new IEntityOperationLogic[] { new Logic() }); EntityUpdate update = new EntityUpdate("Author"); update.Set("FirstName", "John"); update.Set("LastName", "Tolkin"); update.Set("Numberofawards", 2); update.Set("IsAlive", false); EntityUpdate book = new EntityUpdate("book"); book.Set("Title", "The Eye of the World"); book.Set("genre", Genre.Fantasy); svc.Update(book); update.Attach("Book", "author", book.Id.Value); var result = svc.Update(update); Assert.AreEqual(true, result.Success); EntityQuery2 query = new EntityQuery2("Author"); query.AddProperties("FirstName", "LastName", "IsAlive", "CreatedOn"); query.Include("book", "author"); var res = repo.Search(query); Assert.AreEqual(1, res.Count()); var a = res.Single(); Assert.AreEqual("John", a.GetData<string>("Firstname")); Assert.AreEqual("Tolkin", a.GetData<string>("LastName")); var created = a.GetData<DateTime>("createdon"); Assert.AreEqual(DateTime.Now.Date, created.Date); var books = a.GetManyRelations("book", "author"); Assert.AreEqual(1, books.Count()); var b = books.Single().Entity; Assert.AreEqual("The Eye of the World", b.GetData<string>("title")); Assert.AreEqual(Genre.Fantasy, b.GetData<Genre>("genre")); created = b.GetData<DateTime>("createdon"); Assert.AreEqual(DateTime.Now.Date, created.Date); repo.Delete(a, true); repo.Delete(b); }