Update() public method

public Update ( Entity entity ) : void
entity Entity
return void
Esempio n. 1
0
        /// <summary>
        /// تایید اضافه کار تشویقی یک دوره(ماه) توسط اداری جهت پرداخت
        /// </summary>
        /// <param name="year">سال</param>
        /// <param name="month">ماه</param>
        /// <returns>شناسه رکورد</returns>
        public decimal ApproveOverTime(int year, int month)
        {
            DateTime date;

            if (BLanguage.CurrentSystemLanguage == LanguagesName.Parsi)
            {
                date = Utility.ToMildiDate(String.Format("{0}/{1}/{2}", year, month, 1));
            }
            else
            {
                date = new DateTime(year, month, 1);
            }
            //-----------------------------------------------------------------------
            OverTime overTime = this.GetPeriodByDate(date);

            overTime.ApprovedDate = DateTime.Now;
            overTime.IsApproved   = true;
            //این دوره هنوز در دیتابیس تعریف نشده
            if (overTime == null)
            {
                return(0);
            }
            //قبلا تایید شده
            if (overTime.IsApproved == true)
            {
                return(0);
            }

            overTime = overTimeRepository.Update(overTime);
            return(overTime.ID);
        }
Esempio n. 2
0
        public async Task Remove_Tag()
        {
            // Arrange
            await using var context = GetNewContext("Remove_Tag");
            var blogsRepository = new EntityRepository <Blog>(context);
            var tagRepository   = new EntityRepository <Tag>(context);

            var blog = await blogsRepository.Find(1);

            var tag = blog.Tags.FirstOrDefault(x => x.Name == "T05");

            // Act
            blog.Tags.Remove(tag);
            var updatedBlog = await blogsRepository.Update(blog);

            // Assert
            var modifiedBlog = await blogsRepository.Find(1);

            var tagT5 = await tagRepository.FirstOrDefault(x => x.Name == "T05");

            Assert.NotNull(updatedBlog);
            Assert.Equal(2, modifiedBlog.Tags.Count);
            Assert.DoesNotContain("T05", modifiedBlog.Tags.Select(x => x.Name));
            Assert.NotNull(tagT5);
        }
        public ViewResult EditAnnoun(ChordTab chordTab)
        {
            IRepository <ChordTab> chordTabs = new EntityRepository <ChordTab>(SingletonSession.getInstance().sess);
            ChordTab previousAnnoun          = chordTabs.ReadById(chordTab.UID);

            previousAnnoun._Chord = SingletonSession.getInstance().sess.Merge(chordTab._Chord);
            using (ITransaction transaction = SingletonSession.getInstance().sess.BeginTransaction())
            {
                DeletePhoto(HttpContext.Request.Form, previousAnnoun);
                foreach (var file in HttpContext.Request.Form.Files)
                {
                    string path = hosting.WebRootPath + "/images/" + GenerateFileName(chordTab._Chord, file.FileName);
                    using (var fileStream = new FileStream(path, FileMode.Create))
                    {
                        file.CopyTo(fileStream);
                    }
                    Photos photo = new Photos();
                    photo.Name = GenerateFileName(chordTab._Chord, file.FileName);
                    previousAnnoun._Photos.Add(photo);
                }
                chordTabs.Update(previousAnnoun);
                transaction.Commit();
            }
            return(PersonalPage());
        }
Esempio n. 4
0
        public void SetArchiveGridSettings(IList <ArchiveFieldMap> mapList)
        {
            try
            {
                IList <ArchiveFieldMap> orginalMapList = mapRep.GetAll();
                foreach (ArchiveFieldMap changedMap in mapList)
                {
                    ArchiveFieldMap map = orginalMapList.Where(x => x.PId == changedMap.PId).FirstOrDefault();
                    if (map == null)
                    {
                        continue;
                    }
                    if (map.Visible != changedMap.Visible)
                    {
                        map.Visible = changedMap.Visible;
                        mapRep.Update(map);
                    }
                }
            }
            catch (Exception ex)
            {
                BaseBusiness <Entity> .LogException(ex);

                throw ex;
            }
        }
Esempio n. 5
0
        public void TestUpdate()
        {
            using (var repo = new EntityRepository(new DatabaseContext(_options)))
            {
                repo.Insert(new Entity()
                {
                    Name = "Naam"
                });
            }

            using (var repo = new EntityRepository(new DatabaseContext(_options)))
            {
                repo.Update(new Entity()
                {
                    Id   = 1,
                    Name = "Aangepast"
                });
            }


            using (var repo = new EntityRepository(new DatabaseContext(_options)))
            {
                Assert.AreEqual(1, repo.Count());
                Assert.AreEqual("Aangepast", repo.Find(1).Name);
            }
        }
Esempio n. 6
0
        public async Task <EntityResponse> UpdateAsync(int id, T entity)
        {
            var entityExistente = await _entityRepository.FindByIdAsync(id);

            if (entityExistente == null)
            {
                return(new EntityResponse($"{entity.GetType().Name} não encontrada."));
            }


            foreach (PropertyInfo prop in entity.GetType().GetProperties())
            {
                if (prop.Name != "Id")
                {
                    PropertySet(entityExistente, prop.Name, prop.GetValue(entity, null));
                }
            }

            try
            {
                _entityRepository.Update(entityExistente);
                await _unitOfWork.CompleteAsync();

                return(new EntityResponse((IEntity)entityExistente));
            }
            catch (Exception e)
            {
                return(new EntityResponse($"Um erro ocorreu ao atualizar a {entity.GetType().Name}: {e.Message}"));
            }
        }
Esempio n. 7
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="LangID"></param>
        public void SetCurrentLanguage(string LangID)
        {
            EntityRepository <Languages>    langRep        = new EntityRepository <Languages>(false);
            EntityRepository <UserSettings> userSettingRep = new EntityRepository <UserSettings>(false);
            UserRepository rep      = new UserRepository(false);
            User           user     = rep.GetByUserName(this.CurrentUser);
            Languages      language = langRep.GetByCriteria(new CriteriaStruct(Utility.GetPropertyName(() => new Languages().LangID), LangID)).FirstOrDefault();

            if (language != null && user != null)
            {
                UserSettings userSetings = userSettingRep.GetByCriteria(new CriteriaStruct(Utility.GetPropertyName(() => new UserSettings().User), user)).FirstOrDefault();
                if (userSetings != null)
                {
                    userSetings.Language = language;
                    userSettingRep.Update(userSetings);
                }
                else
                {
                    userSetings          = new UserSettings();
                    userSetings.Language = language;
                    userSetings.User     = user;
                    userSettingRep.Save(userSetings);
                }
                SessionHelper.SaveSessionValue(SessionHelper.BussinessLocalLanguageSessionName1, LangID);
                SessionHelper.ClearSessionValue(SessionHelper.BussinessLocalLanguageSessionName2);
            }
            else
            {
                throw new InvalidDatabaseStateException(UIFatalExceptionIdentifiers.UserSettingsLanguageOrUserNotExsists, "زبان یا کاربر در دیتابیس موجود نمیباشد", "GTS.Clock.Business.AppSettings.LanguageProvider.SetCurrentLanguage");
            }
        }
        public void SaveFile(EntityType entityType, int entityId, FileEntity file)
        {
            using (DatabaseContext apiDatabaseContext = CreateDatabaseContext())
            {
                using (File.Data.DatabaseContext fileDatabaseContext = new File.Data.DatabaseContext(DataContext, false))
                {
                    FileRepository   fileRepository   = new FileRepository(fileDatabaseContext);
                    EntityRepository entityRepository = new EntityRepository(apiDatabaseContext);

                    File.Data.VEntityFile entityFile = fileRepository.Save(entityType, entityId, file, x =>
                    {
                        file.FileId = x.FileId;

                        if (x.File.SystemFileName != file.SystemFileName)
                        {
                            _log.Info($"Updating api property file name from {file.SystemFileName} to {x.File.SystemFileName} for id {x.File.FileId}.");
                            x.File.SystemFileName = file.SystemFileName;
                        }
                    });

                    fileDatabaseContext.SaveChanges();

                    // update the entity date value for this file
                    entityRepository.Update(entityFile.File, file.LastUpdated);
                    apiDatabaseContext.SaveChanges();
                }
            }
        }
Esempio n. 9
0
        public async Task Add_ExistingTag()
        {
            // Arrange
            await using var context = GetNewContext("Add_ExistingTag");
            var blogsRepository = new EntityRepository <Blog>(context);
            var tagsRepository  = new EntityRepository <Tag>(context);

            var blog = await blogsRepository.Find(1);

            var tag = await tagsRepository.Find(1);

            // Act
            blog.Tags.Add(tag);
            var updatedBlog = await blogsRepository.Update(blog);

            // Assert
            var modifiedBlog = await blogsRepository.Find(1);

            var tags = await tagsRepository.FindAll();

            Assert.NotNull(updatedBlog);
            Assert.Equal(4, modifiedBlog.Tags.Count);
            Assert.Contains("T01", modifiedBlog.Tags.Select(x => x.Name));
            Assert.Equal(Utilities.Utilities.TagsCount, tags.Count());
        }
Esempio n. 10
0
        private void ModificarEstado(int numero, Estados.EstadoMarco estado)
        {
            Marco marco = this.GetEntidadByNumero(numero);

            marco.Estado = estado;

            EntityRepository.Update(marco);
        }
Esempio n. 11
0
 /// <summary>
 /// ذخیره سطوح دسترسی جانشین در هنگام درج
 /// </summary>
 /// <param name="substitute"></param>
 /// <param name="action"></param>
 protected override void OnSaveChangesSuccess(Substitute substitute, UIActionType action)
 {
     if (action == UIActionType.ADD)
     {
         IList <Precard> list = new ManagerRepository(false).GetAllAccessGroup(substitute.Manager.ID);
         substitute.PrecardList = list;
         objectRep.Update(substitute);
     }
 }
Esempio n. 12
0
        public void SetearEstadoTerminado(int numero)
        {
            Pedido pedido = this.GetEntidadByNumero(numero);

            pedido.Estado         = Estados.EstadoPedido.Terminado;
            pedido.FechaTerminado = DateTime.Now;

            EntityRepository.Update(pedido);
        }
Esempio n. 13
0
 /// <summary>
 /// به روز رسانی تنظیمات جاری سیستم
 /// </summary>
 /// <param name="appSet"></param>
 public static void Update(ApplicationSettings appSet)
 {
     if (appSet.ID > 0)
     {
         EntityRepository <ApplicationSettings> rep = new EntityRepository <ApplicationSettings>(false);
         rep.Update(appSet);
         SessionHelper.ClearSessionValue(SessionHelper.GTSApplicationSettings);
     }
 }
Esempio n. 14
0
        public void Actualizar(VarillaDTO dto)
        {
            Varilla varilla = EntityRepository.GetById(dto.Id);

            varilla.Disponible = dto.Disponible;
            varilla.Cantidad   = dto.Cantidad;
            varilla.Precio     = dto.Precio;

            EntityRepository.Update(varilla);
        }
Esempio n. 15
0
        public async Task SendPushNotification(int id)
        {
            using (var repository = new EntityRepository(new BaitkmDbContext(new DbContextOptions <BaitkmDbContext>())))
            {
                var pushNotification = await repository.Filter <PushNotification>(x => x.Id == id).FirstOrDefaultAsync();

                if (pushNotification == null)
                {
                    return;
                }
                var userIds  = new List <int>();
                var guestIds = new List <int>();
                switch (pushNotification.PushNotificationUserType)
                {
                case PushNotificationUserType.All:
                    userIds = await repository.GetAll <User>().Select(x => x.Id).ToListAsync();

                    guestIds = await repository.GetAll <Guest>().Select(x => x.Id).ToListAsync();

                    break;

                case PushNotificationUserType.Guest:
                    guestIds = await repository.GetAll <Guest>().Select(x => x.Id).ToListAsync();

                    break;

                case PushNotificationUserType.Registered:
                    userIds = await repository.GetAll <User>().Select(x => x.Id).ToListAsync();

                    break;

                default:
                    throw new ArgumentOutOfRangeException();
                }
                using (var fireBaseRepository = new FirebaseRepository(new BaitkmDbContext(new DbContextOptions <BaitkmDbContext>())))
                {
                    await fireBaseRepository.SendCampaignNotification(new FirebaseCampaignNotificationModel
                    {
                        Description = pushNotification.Description,
                        PushNotificationActionType = pushNotification.PushNotificationActionType,
                        Title     = pushNotification.Title,
                        UserIds   = userIds,
                        GuestIds  = guestIds,
                        FromAdmin = true,
                        SenderId  = null
                    });
                }
                pushNotification.PushNotificationStatusType = PushNotificationStatusType.Sent;
                repository.Update(pushNotification);
                await repository.SaveChangesAsync();
            }
        }
Esempio n. 16
0
        protected virtual void Update(T obj)
        {
            try
            {
                objRepository.Update(obj);
            }
            catch (Exception ex)
            {
                LogException(ex, typeof(T).Name + " - " + "GTS.Clock.Business-Nhibernate Action");

                throw ex;
            }
        }
        public override void ApplyChanges()
        {
            if (IsNew)
            {
                EntityRepository.Add(this.Entity);
            }
            else
            {
                EntityRepository.Update(this.Entity);
            }

            DialogHostExtensions.CloseCurrent();
        }
Esempio n. 18
0
        public async Task <ActionResult> LoadMangaInfo([FromBody] MangaInfo item)
        {
            if (item == null)
            {
                return(BadRequest("Manga info is nulll"));
            }
            item = await _mangaLoader.LoadMangaInfoAsync(item);

            _chaptersRep.Delete(chapter => chapter.Manga.Id == item.Id);
            _chaptersRep.Save();
            EntityRepository.Update(item);
            EntityRepository.Save();
            return(Ok());
        }
Esempio n. 19
0
 /// <summary>
 /// ذخیره سطوح دسترسی جانشین در هنگام درج
 /// </summary>
 /// <param name="substitute"></param>
 /// <param name="action"></param>
 protected override void OnSaveChangesSuccess(Substitute substitute, UIActionType action)
 {
     if (action == UIActionType.ADD)
     {
         IList <Precard> list = new ManagerRepository(false).GetAllAccessGroup(substitute.Manager.ID);
         substitute.PrecardList = list;
         objectRep.Update(substitute);
         new BRole().SetUserRole(substitute.Person, RoleCustomCode.Substitute);
     }
     if (action == UIActionType.EDIT)
     {
         new BRole().SetUserRole(substitute.Person, RoleCustomCode.Substitute);
     }
 }
        public void TestUpdateCompany()
        {
            var currentTestContactRepository = new EntityRepository <Contact>("Contact");

            var contact = DataGenerator.Build("John");

            contact.Identifier = currentTestContactRepository.Create(contact);

            var newCompanyName = "NewCompany";

            contact.Company = newCompanyName;
            currentTestContactRepository.Update(contact);

            Assert.AreEqual(newCompanyName, currentTestContactRepository.Get(contact.Identifier.Value).Company);
        }
Esempio n. 21
0
        public override TResultDto Update <TDto, TResultDto>(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);

            var updatedEntity = EntityRepository.Update(entity);

            return(Mapper.Map <TResultDto>(updatedEntity));
        }
        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());
        }
Esempio n. 23
0
        public async Task <ActionResult> ReadNotifications(Guid[] notifications)
        {
            var items = await EntityRepository.GetByAsync(item => notifications.Contains(item.Id));

            bool save = false;

            items.ForEach(item => {
                item.IsRead = true;
                EntityRepository.Update(item);
                save = true;
            });
            if (save)
            {
                EntityRepository.Save();
            }
            return(Ok());
        }
        public void TestRepository_Update_Success()
        {
            // Log results.
            var log = (Globals.LOG_TO_FILE == true ? sw : Console.Out);

            try
            {
                // Change this value to test adding x number of people
                int recordsToCreate = 1;
                int IdToUpdate      = 1;

                // Arrange
                // 1. Create Mock dbSet
                FakeDbSet <Person> FakeDbSet = new FakeDbSet <Person>();
                // 2. Add records to Mock dbSet
                IEnumerable <Person> recordList = AddPeopleToFakeDbSet(FakeDbSet, recordsToCreate);
                // 3. Create Mock db context
                Mock <IPeopleContext> MockdDbContextObject = new Mock <IPeopleContext>();
                // 4. Create Repository from Fake dbSet
                EntityRepository <Person> repository = CreateRepository(MockdDbContextObject, FakeDbSet);
                // Act
                Person originalRecord   = recordList.ElementAt(IdToUpdate - 1);
                IEnumerator <Person> en = recordList.GetEnumerator();
                while (en.MoveNext())
                {
                    Person addedRecord = repository.Add(en.Current);
                }
                Person updatedRecord = recordList.FirstOrDefault(x => x.Id == IdToUpdate);
                updatedRecord.Name += "Updated";
                Person storedPerson = repository.Update(updatedRecord);

                // Assert
                MockdDbContextObject.Verify(pc => pc.Set <Person>(), Times.Once());
                Assert.NotSame(originalRecord, updatedRecord);
                Assert.Same(updatedRecord, storedPerson);

                // Log success
                log.WriteLine("{0}(): Passed - record {1} updated\n", MethodBase.GetCurrentMethod().Name, IdToUpdate);
            }
            //Log failure
            catch (Exception ex)
            {
                // Log failure
                log.WriteLine("{0}(): Failed - Exception: {1} Stack: {2}\n", MethodBase.GetCurrentMethod().Name, ex.GetBaseException(), ex.StackTrace);
            }
        }
Esempio n. 25
0
        public async Task Change_Name()
        {
            // Arrange
            await using var context = GetNewContext("Change_Name");
            var blogsRepository = new EntityRepository <Blog>(context);

            var blog = await blogsRepository.Find(1);

            blog.Name += " Modified";

            // Act
            var updatedBlog = await blogsRepository.Update(blog);

            // Assert
            var modifiedBlog = await blogsRepository.Find(1);

            Assert.NotNull(updatedBlog);
            Assert.Equal("A01 Modified", modifiedBlog.Name);
        }
Esempio n. 26
0
        public void Update_UpdateModelSet_MappedToUpdateEntitySet()
        {
            var repositoryProvider = new Mock <IRepositoryProvider>();
            var definitionProvider = new DataAnnotationsDefinitionProvider();

            repositoryProvider.Setup(provider => provider.EntityDefinitionProvider).Returns(definitionProvider);
            repositoryProvider.Setup(provider => provider.Update(It.IsAny <UpdateSet <SubSubRow> >())).Returns(1);

            int actual;

            using (var provider = repositoryProvider.Object)
            {
                var repository = new EntityRepository <SubSubEntity, SubSubRow>(provider, this.mapper);
                actual = repository.Update(
                    new UpdateSet <SubSubEntity>().Set(entity => entity.UniqueName, "newName")
                    .Where(filterSet => filterSet.AreEqual(entity => entity.UniqueName, "bar")));
            }

            Assert.AreEqual(1, actual);
        }
Esempio n. 27
0
        public bool EntityUpdate <TEntity>(IEntity entity) where TEntity : IEntity
        {
            bool success = false;

            try
            {
                ApplicationPlatformContext <TEntity> ContextEntity = new ApplicationPlatformContext <TEntity>();
                ContextEntity.Initialized();
                EntityRepository <TEntity> repository = new EntityRepository <TEntity>(ContextEntity, entity, false);
                repository.Update(entity);
            }
            catch (SqliteException ex)
            {
                SqLiteExceptionHandler <SqliteException> error = new SqLiteExceptionHandler <SqliteException>(ex);
                LoggerHelper.LogConsole("Database Error : ");
                LoggerHelper.LogConsole("Description" + error.GetDescription());
                LoggerHelper.LogConsole("TrackTrace" + error.GetTrackTrace());
            }
            return(success);
        }
Esempio n. 28
0
        public async Task UnBlock()
        {
            using (var repository = new EntityRepository(new BaitkmDbContext(new DbContextOptions <BaitkmDbContext>())))
            {
                var users = await repository.Filter <User>(x => x.IsBlocked).ToListAsync();

                if (users == null)
                {
                    return;
                }
                foreach (var item in users)
                {
                    dynamic property = new ExpandoObject();
                    item.IsBlocked      = false;
                    item.UserStatusType = UserStatusType.Active;
                    repository.Update(item);
                }
                await repository.SaveChangesAsync();
            }
        }
Esempio n. 29
0
        public async Task Deactivate()
        {
            //TODO for TOP ANNOUNCEMENT
            using (var repository = new EntityRepository(new BaitkmDbContext(new DbContextOptions <BaitkmDbContext>())))
            {
                var announcements = await repository.Filter <Announcement>(x => !x.IsDraft && x.AnnouncementStatus == AnnouncementStatus.Accepted).ToListAsync();

                if (announcements == null)
                {
                    return;
                }
                announcements = announcements.Where(x => x.AnnouncementStatusLastDay.Date == DateTime.Today.Date).ToList();
                foreach (var item in announcements)
                {
                    item.AnnouncementStatus = AnnouncementStatus.Expired;
                    repository.Update(item);
                }
                await repository.SaveChangesAsync();
            }
        }
Esempio n. 30
0
        public async Task Add_Tag()
        {
            // Arrange
            await using var context = GetNewContext("Add_Tag");
            var blogsRepository = new EntityRepository <Blog>(context);

            var blog = await blogsRepository.Find(1);

            // Act
            blog.Tags.Add(new Tag {
                Name = "New Tag"
            });
            var updatedBlog = await blogsRepository.Update(blog);

            // Assert
            var modifiedBlog = await blogsRepository.Find(1);

            Assert.NotNull(updatedBlog);
            Assert.Equal(4, modifiedBlog.Tags.Count);
            Assert.Contains("New Tag", modifiedBlog.Tags.Select(x => x.Name));
        }
Esempio n. 31
0
        public void Test_EntityRepo_Update()
        {
            var dbService = new TestDatabaseService();
            var repository = new EntityRepository(dms, dbService, new SequenceProvider(dbService));
            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
                };

                repository.Create(jordan);
                repository.Create(feist);
                repository.Create(fb1);
                repository.Create(fb2);
                repository.Attach(feist, new Relation("author", fb1));
                repository.Attach(feist, new Relation("author", fb2));
                #endregion

                jordan.LastName += "EDIT";
                jordan.IsAlive = true;
                jordan.Born = jordan.Born.AddDays(2.0);
                jordan.Rating -= 0.5m;

                repository.Update(jordan);
                var q = new EntityQuery2("author", jordan.Id);
                q.AddProperties("lastname", "isalive", "born", "rating");
                var e = repository.Read(q);
                var updated = new Author(e);
                Assert.AreEqual(jordan.LastName, updated.LastName);
                Assert.AreEqual(jordan.Born, updated.Born);
                Assert.AreEqual(jordan.IsAlive, updated.IsAlive);
                Assert.AreEqual(jordan.Rating, updated.Rating);
            }
        }
Esempio n. 32
0
        //[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());
            }
        }