public void Add(BusinessObjects.GroupRelation entity)
        {
            //Add GroupRelation
            using (_GroupRelationRepository = new GenericRepository<DAL.DataEntities.GroupRelation>())
            {
                _GroupRelationRepository.Add((DAL.DataEntities.GroupRelation)entity.InnerEntity);
                _GroupRelationRepository.SaveChanges();
            }

            //Add GroupRelations_To_Features
            using (_GroupRelationsToFeaturesRepository = new GenericRepository<DAL.DataEntities.GroupRelation_To_Feature>())
            {

                foreach (int childFeatureID in entity.ChildFeatureIDs)
                {
                    DAL.DataEntities.GroupRelation_To_Feature grToFeature = new DAL.DataEntities.GroupRelation_To_Feature();
                    grToFeature.GroupRelationID = entity.ID;
                    grToFeature.ParentFeatureID = entity.ParentFeatureID;
                    grToFeature.ChildFeatureID = childFeatureID;

                    _GroupRelationsToFeaturesRepository.Add(grToFeature);
                }

                _GroupRelationsToFeaturesRepository.SaveChanges();
            }
        }
        public void Add(BusinessObjects.FeatureSelection entity)
        {
            using (_FeatureSelectionRepository = new GenericRepository<DAL.DataEntities.FeatureSelection>())
            {
                //Add the FeatureSelection
                _FeatureSelectionRepository.Add((DAL.DataEntities.FeatureSelection)entity.InnerEntity);
                _FeatureSelectionRepository.SaveChanges();

                //Add AttributeValues
                using (_AttributeValuesRepository = new GenericRepository<DAL.DataEntities.AttributeValue>())
                {
                    for (int i = entity.AttributeValues.Count - 1; i >= 0; i--)
                    {
                        BLL.BusinessObjects.AttributeValue BLLAttributeValue = entity.AttributeValues[i];
                        BLLAttributeValue.FeatureSelectionID = entity.ID;

                        //Add
                        if (BLLAttributeValue.ToBeDeleted == false && BLLAttributeValue.ID == 0)
                        {
                            _AttributeValuesRepository.Add((DAL.DataEntities.AttributeValue)BLLAttributeValue.InnerEntity);
                        }
                    }
                    _AttributeValuesRepository.SaveChanges();
                }
            }
        }
Exemplo n.º 3
0
        private void DropFileInCategory(object sender, DragEventArgs e)
        {
            ImageService imgService = new ImageService();
            string[] fileList = e.Data.GetData(DataFormats.FileDrop) as string[];
            string fileextension = Path.GetExtension(fileList[0]);
            if (fileextension != ".pdf")
            {
                MessageBox.Show("Not allowed Drag'n'Drop for this file type");
            }
            else
            {
                string filename = Path.GetFileNameWithoutExtension(fileList[0]);
                string pathtofile = Path.GetFullPath(fileList[0]);
               
                string pathtobookimage = imgService.GenerateImage(pathtofile);
                FileInfo fileToAdd = new FileInfo(pathtofile);
                int size = (int)fileToAdd.Length;

                var book = new Book()
                {
                    Name = filename,
                    FileType = fileextension,
                    Path = pathtofile,
                    PathToBookImg = pathtobookimage,
                    Author = "Unknown Author",
                    Size = size
                };
                Debug.WriteLine(book.Name);
                _categoriesRepository = IoCManager.Kernel.Get<IRepository<Category>>();
                var concreteCategory = _categoriesRepository.GetByQery(q => q.Name == "Foreign Literature");
                concreteCategory.FirstOrDefault().Books.Add(book);
                _categoriesRepository.SaveChanges();
                MessageBox.Show("Book was added");
            }
        }
Exemplo n.º 4
0
 public void Add(BusinessObjects.Model entity)
 {
     using (_ModelRepository = new GenericRepository<DAL.DataEntities.Model>())
     {
         _ModelRepository.Add((DAL.DataEntities.Model)entity.InnerEntity);
         _ModelRepository.SaveChanges();
     }
 }
 public void Add(BusinessObjects.CustomRule entity)
 {
     using (_CustomRuleRepository = new GenericRepository<DAL.DataEntities.CustomRule>())
     {
         _CustomRuleRepository.Add((DAL.DataEntities.CustomRule)entity.InnerEntity);
         _CustomRuleRepository.SaveChanges();
     }
 }
Exemplo n.º 6
0
 public void Add(BusinessObjects.Relation entity)
 {
     using (_RelationRepository = new GenericRepository<DAL.DataEntities.Relation>())
     {
         _RelationRepository.Add((DAL.DataEntities.Relation)entity.InnerEntity);
         _RelationRepository.SaveChanges();
     }
 }
 public void Add(BLL.BusinessObjects.UITemplate entity)
 {
     using (_UITemplateRepository = new GenericRepository<DAL.DataEntities.UITemplate>())
     {
         _UITemplateRepository.Add((DAL.DataEntities.UITemplate)entity.InnerEntity);
         _UITemplateRepository.SaveChanges();
     }
 }
 public void Add(BusinessObjects.Constraint entity)
 {
     using (_ConstraintRepository = new GenericRepository<DAL.DataEntities.Constraint>())
     {
         _ConstraintRepository.Add((DAL.DataEntities.Constraint)entity.InnerEntity);
         _ConstraintRepository.SaveChanges();
     }
 }
Exemplo n.º 9
0
 public void Add(BusinessObjects.Feature entity)
 {
     using (_FeatureRepository = new GenericRepository<DAL.DataEntities.Feature>())
     {
         //Add the Feature
         _FeatureRepository.Add((DAL.DataEntities.Feature)entity.InnerEntity);
         _FeatureRepository.SaveChanges();
     }
 }
Exemplo n.º 10
0
 public void Add(BusinessObjects.Attribute entity)
 {
     using (_AttributeRepository = new GenericRepository<DAL.DataEntities.Attribute>())
     {
         //Add the Attribute
         _AttributeRepository.Add((DAL.DataEntities.Attribute)entity.InnerEntity);
         _AttributeRepository.SaveChanges();
     }
 }
Exemplo n.º 11
0
 public void Delete(int id)
 {
     DAL.DataEntities.Model model;
     using (_ModelRepository = new GenericRepository<DAL.DataEntities.Model>())
     {
         model = _ModelRepository.SingleOrDefault(m => m.ID == id);
         _ModelRepository.Delete(model);
         _ModelRepository.SaveChanges();
     }
 }
 public void Delete(int id)
 {
     DAL.DataEntities.Configuration DALConfiguration;
     using (_ConfigurationRepository = new GenericRepository<DAL.DataEntities.Configuration>())
     {
         DALConfiguration = _ConfigurationRepository.SingleOrDefault(m => m.ID == id);
         _ConfigurationRepository.Delete(DALConfiguration);
         _ConfigurationRepository.SaveChanges();
     }
 }
Exemplo n.º 13
0
 public void Delete(int id)
 {
     DAL.DataEntities.UITemplate template;
     using (_UITemplateRepository = new GenericRepository<DAL.DataEntities.UITemplate>())
     {
         template = _UITemplateRepository.SingleOrDefault(m => m.ID == id);
         _UITemplateRepository.Delete(template);
         _UITemplateRepository.SaveChanges();
     }
 }
Exemplo n.º 14
0
 private static void EnsureMember(IRepository<Member> memberRepository)
 {
     if (!memberRepository.GetAll().Any(m => m.Name == "Sherlock Holmes"))
     {
         memberRepository.Add(new Member
         {
             Name = "Sherlock Holmes"
         });
         memberRepository.SaveChanges();
     }
 }
Exemplo n.º 15
0
        public Hotel.Database.Model.Hotel Execute(HotelEditModel model)
        {
            var hotel = _hotelRepo.Get(model.Id);

            hotel.Address      = model.Address;
            hotel.IndividualId = model.IndividualId;
            hotel.Title        = model.Title;

            _hotelRepo.AddOrUpdate(hotel);
            _hotelRepo.SaveChanges();

            return(hotel);
        }
Exemplo n.º 16
0
        public ArticleDto UpdateArticleWithCommitHistory(ArticleDto articleDto)
        {
            Share.Models.Article.Entities.Article articleExisting = _articleRepository.Entities.Include(a => a.ArticleLicense).Single(a => a.ArticleId == articleDto.ArticleId);
            if (!string.Equals(articleExisting?.ArticleLicense?.License, articleDto?.ArticleLicenseDto?.License))
            {
                articleDto.ArticleLicenseDto.LicensedDate = DateTime.UtcNow;
            }
            articleExisting = _mapper.Map <ArticleDto, Share.Models.Article.Entities.Article>(articleDto, articleExisting);
            int        i             = _articleRepository.SaveChanges();
            ArticleDto articleDtoNew = _mapper.Map <ArticleDto>(articleExisting);

            return(articleDtoNew);
        }
Exemplo n.º 17
0
        public void DeleteVersion(Guid id)
        {
            var productVersion = _productVersionRepository.GetByID(id);

            if (productVersion == null)
            {
                throw new BusinessException(ExceptionCode.ProductVersionDoesNotExist);
            }

            productVersion.SoftDelete = true;
            _productVersionRepository.Update(productVersion);
            _productVersionRepository.SaveChanges();
        }
Exemplo n.º 18
0
        public void DeleteGenreMovies(int id)
        {
            var genreMovies = Entities.Where(x => x.MovieId == id);

            foreach (var genreMovie in genreMovies)
            {
                genreMovie.Status           = Status.Deleted;
                genreMovie.ModificationDate = DateTime.Now;

                _repository.Update(genreMovie);
            }
            _repository.SaveChanges();
        }
Exemplo n.º 19
0
        public void ModifyOrder(int id, decimal totalDue)
        {
            using (IRepository repository = CreateUnitOfWork())
            {
                SalesOrderHeader order = repository
                                         .GetEntities <SalesOrderHeader>().FirstOrDefault(o => o.Id == id);

                order.TotalDue = totalDue;
                order.TaxAmt   = CalculateTax(order);

                repository.SaveChanges();
            }
        }
Exemplo n.º 20
0
        public int DeleteSalary(int employeeNumber, DateTime fromDate)
        {
            Salary salary = GetOneSalary(employeeNumber, fromDate);

            if (salary == null)
            {
                return(-1);
            }

            _salaryRepository.Remove(salary);
            _salaryRepository.SaveChanges();
            return(1);
        }
Exemplo n.º 21
0
        public bool Save(User user)
        {
            bool isUserAdded   = false;
            User duplicateUser = _repository.Users.FirstOrDefault(a => a.Name.Equals(user.Name));

            if (duplicateUser == null)
            {
                _repository.Users.Add(user);
                isUserAdded = _repository.SaveChanges() > 0;
            }

            return(isUserAdded);
        }
        public Token GetToken(string userId)
        {
            var isUserValid = userRepository.Where(u => u.Id == userId).Any();

            if (!isUserValid)
            {
                return(null);
            }
            var userIdString = userId;
            var today        = DateTime.Now;
            var acceptToken  = GenerateToken();
            var newToken     = new Token
            {
                UserId         = userIdString,
                AccessToken    = acceptToken,
                ExpirationDate = today.AddDays(30)
            };

            tokenRepository.Add(newToken);
            tokenRepository.SaveChanges();
            return(newToken);
        }
Exemplo n.º 23
0
        public void AddClient(CreateClientDTO clientDto)
        {
            var client = new Client()
            {
                BirthDate = clientDto.BirthDate,
                AddedDate = DateTime.Now,
                FirstName = clientDto.FirstName,
                LastName  = clientDto.LastName,
                Contacts  = new Contacts()
                {
                    Email     = clientDto.Email,
                    Phone1    = clientDto.Phone1,
                    Phone2    = clientDto.Phone2,
                    Facebook  = clientDto.Facebook,
                    Instagram = clientDto.Instagram,
                    Website   = clientDto.Website
                }
            };

            _repository.Add(client);
            _repository.SaveChanges();
        }
Exemplo n.º 24
0
 private static void EnsureProduct(Rebate rebate, IRepository <Product> productRepository)
 {
     if (!productRepository.GetAll().Any(p => p.ProductNumber == 11190))
     {
         productRepository.Add(new Product
         {
             ProductNumber = 11190,
             Name          = "Procrit",
             Rebate        = rebate
         });
         productRepository.SaveChanges();
     }
 }
Exemplo n.º 25
0
        public override void ExecuteMigration(IRepository repository)
        {
            // Remove all tables from the database.
            // GetDbEntitys will return all type that containes a property with PrimaryKey attribute
            MethodHelper.GetDbEntitys(this.GetType().Assembly)
            .ForEach(repository.RemoveTable);

            // Now create all the tables structures for our modules
            MethodHelper.GetDbEntitys(this.GetType().Assembly)
            .ForEach(x => repository.CreateTable(x));
            base.ExecuteMigration(repository);
            repository.SaveChanges();
        }
Exemplo n.º 26
0
        public NewUserAPIModel CreateNewUser(NewUserBindingModel model)
        {
            if (model == null)
            {
                throw new ArgumentNullException("RegisterViewModel can not be null.");
            }
            if (string.IsNullOrWhiteSpace(model.Email) || string.IsNullOrWhiteSpace(model.Password))
            {
                throw new ArgumentException("Email and Password can not be null/empty.");
            }
            var exists = _repo.Where(x => x.Email == model.Email).Any();

            if (exists)
            {
                throw new EmailDuplicateException("User with such email already exists.");
            }
            var newUser = _mapper.Map <UserDb>(model);

            _repo.Add(newUser);
            _repo.SaveChanges();
            return(_mapper.Map <NewUserAPIModel>(newUser));
        }
        public IHttpActionResult PostCustomer([FromBody] Customer customer)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (customer.CustomerID == null || CustomerExists(customer.CustomerID))
            {
                return(BadRequest("Invalid CustomerID"));
            }

            if (customer.CompanyName == null)
            {
                return(BadRequest("Invalid CompanyName"));
            }

            repo.Create(customer);
            repo.SaveChanges();

            return(CreatedAtRoute("DefaultApi", new { id = customer.CustomerID }, customer));
        }
        public int Handle(AddCompanyCommand command)
        {
            var company = new Company
            {
                CompanyName = command.Name
            };

            _companyRepository.Add(company);
            _companyRepository.SaveChanges();
            _audit.Audit(string.Format("Company added by with Id {0}", company.Id), command.CreatedById);

            return(company.Id);
        }
        public async Task <ActionResult <Aluno> > PostAluno(AlunoRegistrarDto alunoDto)
        {
            //Pega alunoDto e transforma em aluno
            var aluno = _mapper.Map <Aluno>(alunoDto);

            _repository.Add(aluno);
            // if (_repository.SaveChanges())
            // {
            //     return Ok(aluno);
            // }

            if (_repository.SaveChanges())
            {
                return(Created($"/api/aluno/{alunoDto.Id}", _mapper.Map <AlunoDto>(aluno)));
            }

            // _smartContext.Add(aluno);
            // _smartContext.SaveChanges();
            //return Ok(aluno);

            return(BadRequest("Aluno não cadastrado"));
        }
Exemplo n.º 30
0
        public void DeleteConnectionPaths(int id)
        {
            var connectionPaths = Entities.Where(x => x.Id == id);

            foreach (var connectionPath in connectionPaths)
            {
                connectionPath.Status           = Status.Deleted;
                connectionPath.ModificationDate = DateTime.Now;

                _repository.Update(connectionPath);
            }
            _repository.SaveChanges();
        }
        public bool AddConnection(string user1, string user2)
        {
            var connection = new Connection
            {
                User1Id = user1,
                User2Id = user2
            };

            connections.Add(connection);
            connections.SaveChanges();

            return(true);
        }
Exemplo n.º 32
0
        public IActionResult Post([FromBody] AddFoodModel model)
        {
            Food food = new Food(model);

            _foodrepo.Add(food);
            if (_foodrepo.SaveChanges() == 0)
            {
                throw new ApplicationException("failed to create food");
            }
            var foodDto = _foodMapper.MapFoodDto(food);

            return(Ok(foodDto));
        }
Exemplo n.º 33
0
 private static void EnsureProduct(Rebate rebate, IRepository<Product> productRepository)
 {
     if (!productRepository.GetAll().Any(p => p.ProductNumber == 11190))
     {
         productRepository.Add(new Product
         {
             ProductNumber = 11190,
             Name = "Procrit",
             Rebate = rebate
         });
         productRepository.SaveChanges();
     }
 }
        public void Save(Product product)
        {
            if (product.Id == 0)
            {
                repo.Add(product);
            }
            else
            {
                repo.Update(product);
            }

            repo.SaveChanges();
        }
Exemplo n.º 35
0
        public bool Insert(SecurityUser pSecurityUser)
        {
            try
            {
                //pSecurityUser.ID = GetMaxID();
                pSecurityUser.UserCode     = GetMaxCode();
                pSecurityUser.LoginName    = pSecurityUser.LoginName.ToUpper();
                pSecurityUser.EmployeeCode = pSecurityUser.EmployeeCode.ToUpper();
                pSecurityUser.EmployeeName = pSecurityUser.EmployeeName.ToUpper();
                pSecurityUser.CreateBy     = "Administrator";
                pSecurityUser.CreateDate   = DateTime.Now;

                rep.Add(pSecurityUser);
                rep.SaveChanges();

                return(true);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        public IActionResult Post([FromBody] ProductTemplateFrom model)
        {
            if (!ModelState.IsValid)
            {
                return(new BadRequestObjectResult(ModelState));
            }

            var productTemplate = new ProductTemplate
            {
                Name = model.Name
            };

            foreach (var attributeVm in model.Attributes)
            {
                productTemplate.AddAttribute(attributeVm.Id);
            }

            _productTemplateRepository.Add(productTemplate);
            _productAttributeRepository.SaveChanges();

            return(Ok());
        }
Exemplo n.º 37
0
        public ActionResult Delete(int Id)
        {
            var storyEntity = _story.All()
                              .Where(x => x.StoryID == Id)
                              .FirstOrDefault();
            var path = System.IO.Path.Combine(Server.MapPath("~/Content/Pictures/"), storyEntity.ImageUrl);

            System.IO.File.Delete(path);
            _story.Delete(storyEntity);
            _story.SaveChanges();
            return(RedirectToAction("Index"));
            // return View();
        }
        public IActionResult Post([FromBody] ProductWidgetForm model)
        {
            if (ModelState.IsValid)
            {
                var widgetInstance = new WidgetInstance
                {
                    Name         = model.Name,
                    WidgetId     = 3,
                    WidgetZoneId = model.WidgetZoneId,
                    PublishStart = model.PublishStart,
                    PublishEnd   = model.PublishEnd,
                    DisplayOrder = model.DisplayOrder,
                    Data         = JsonConvert.SerializeObject(model.Setting)
                };

                _widgetInstanceRepository.Add(widgetInstance);
                _widgetInstanceRepository.SaveChanges();
                return(CreatedAtAction(nameof(Get), new { id = widgetInstance.Id }, null));
            }

            return(BadRequest(ModelState));
        }
Exemplo n.º 39
0
    public async Task <Unit> Handle(ChangeReservationSeat command, CancellationToken cancellationToken)
    {
        var reservation = await repository.FindById(command.ReservationId, cancellationToken)
                          ?? throw NotFoundException.For <Reservation>(command.ReservationId);

        reservation.ChangeSeat(command.SeatId);

        await repository.Update(reservation, cancellationToken);

        await repository.SaveChanges(cancellationToken);

        return(Unit.Value);
    }
Exemplo n.º 40
0
        public IActionResult Delete(long id)
        {
            var user = _userRepository.Query().FirstOrDefault(x => x.Id == id);

            if (user == null)
            {
                return(new NotFoundResult());
            }

            user.IsDeleted = true;
            _userRepository.SaveChanges();
            return(Json(true));
        }
Exemplo n.º 41
0
        public void AddPhoto(PhotoDTO newPhoto, string url)
        {
            Photo photo = new Photo {
                ImageURL    = url,
                Title       = newPhoto.Title,
                Rating      = newPhoto.Rating,
                Description = newPhoto.Description,
            };

            _repo.Add <Photo>(photo);
            _repo.SaveChanges();
            //return Mapper.Map<PhotoDTO>(photo);
        }
Exemplo n.º 42
0
        public IActionResult Post([FromBody] AddBeverageModel model)
        {
            Beverage Beverage = new Beverage(model);

            _beverageRepo.Add(Beverage);
            if (_beverageRepo.SaveChanges() == 0)
            {
                throw new ApplicationException("failed to create Beverage");
            }
            var BeverageDto = _beverageMapper.MapBeverageDto(Beverage);

            return(Ok(BeverageDto));
        }
Exemplo n.º 43
0
        public ServiceResult <UserModel> AddUser(UserModel user)
        {
            var entity = new User
            {
                username = user.username,
                name     = user.name,
                password = user.password
            };
            var result = _userRepository.Add(entity);

            _userRepository.SaveChanges();
            return(ServiceResult <UserModel> .SuccessResult(user));
        }
Exemplo n.º 44
0
        public ServiceResult <ChannelModel> AddChannel(ChannelModel channel)
        {
            var entity = new Channel
            {
                theme = channel.theme,
                name  = channel.name
            };
            var result = _channelRepository.Add(entity);

            _channelRepository.SaveChanges();
            channel.id = entity.id;
            return(ServiceResult <ChannelModel> .SuccessResult(channel));
        }
Exemplo n.º 45
0
        public void Test_add_like_to_article()
        {
            // Arrange
            utils.CleanTables();
            Tuple <string, string> userIds = utils.CreateUsers();
            int articleId = utils.CreateSingleArticle(userIds.Item2);
            IDataAccessAdapter adapter = container.Resolve <IDataAccessAdapter>();
            Like like = repo.Create();

            like.CreatedDate = DateTime.Now;
            like.UserId      = userIds.Item1;
            like.ArticleId   = articleId;

            // Act
            repo.Add(like);
            repo.SaveChanges();
            var articles = adapter.GetEntities <Article>();

            // Assert
            Assert.AreEqual(1, articles.Single(n => n.Id == articleId).Likes.Count());
            Assert.AreEqual(userIds.Item1, articles.Single(n => n.Id == articleId).Likes.ElementAt(0).AspNetUser.Id);
        }
Exemplo n.º 46
0
 private static Rebate EnsureRebate(IRepository<Rebate> rebateRepository)
 {
     Rebate rebate = rebateRepository.GetAll().FirstOrDefault(r => r.Name == "Procrit Rebate");
     if (rebate == null)
     {
         rebate = rebateRepository.Add(new Rebate
         {
             Name = "Procrit Rebate"
         });
         rebateRepository.SaveChanges();
     }
     return rebate;
 }
Exemplo n.º 47
0
        public void MyTestInitialize()
        {
            var context = GetProfileContext();
            ContextSession.Current = context;
            //CallContext.SetData(ServiceContextManager<ServiceContext>.SESSIONCOTEXTKEY, context);

            _repository = RepositoryContext.GetRepository();
            //清理垃圾数据
            var rubbish = _repository.GetAll<Category>();
            if (rubbish == null || rubbish.Count() <= 0) return;
            foreach (var item in rubbish)
                this._repository.Remove(item);

            _repository.SaveChanges();
        }
Exemplo n.º 48
0
 public static ApplicationSetting AddTo(this ApplicationSetting item, IRepository repository)
 {
     repository.Add(item);
     repository.SaveChanges();
     return item;
 }
Exemplo n.º 49
0
        public void Delete(int id)
        {
            DAL.DataEntities.Feature feature;
            using (_FeatureRepository = new GenericRepository<DAL.DataEntities.Feature>())
            {
                feature = _FeatureRepository.SingleOrDefault(m => m.ID == id);

                //Cascade delete on all related FeatureSelections
                using (_FeatureSelectionRepository = new GenericRepository<DAL.DataEntities.FeatureSelection>())
                {
                    IEnumerable<DAL.DataEntities.FeatureSelection> featureSelections = _FeatureSelectionRepository.Find(k => k.FeatureID == feature.ID);
                    foreach (DAL.DataEntities.FeatureSelection featureSelection in featureSelections)
                    {
                        _FeatureSelectionRepository.Delete(featureSelection);
                    }

                    _FeatureSelectionRepository.SaveChanges();
                }

                //
                _FeatureRepository.Delete(feature);
                _FeatureRepository.SaveChanges();
            }
        }
Exemplo n.º 50
0
        public void UpdateName(int modelID, string newName)
        {
            using (_ModelRepository = new GenericRepository<DAL.DataEntities.Model>())
            {
                DAL.DataEntities.Model model = _ModelRepository.SingleOrDefault(m => m.ID == modelID);
                model.LastModifiedDate = DateTime.Now;
                model.Name = newName;

                //_ModelRepository.Attach(model);
                _ModelRepository.SaveChanges();
            }
        }
Exemplo n.º 51
0
        internal static void SeedData(IRepository repository)
        {
            Console.WriteLine("Seeding data...");

            // Seed Persons
            var persons = new List<Person>
                              {
                                  new Person {FirstName = "Arthur", LastName = "Smith", Gender = "M"},
                                  new Person {FirstName = "Bert", LastName = "Jones", Gender = "M"},
                                  new Person {FirstName = "Charlie", LastName = "Robertson", Gender = "M"}
                              };

            persons.ForEach(p => repository.Insert(p));

            // Seed Regions
            var regions = new List<Region>
                              {
                                  new Region {Name = "Banff National Park - South", Description = "Banff National Park"},
                                  new Region {Name = "Jasper National Park"},
                                  new Region {Name = "Kootenay National Park"},
                                  new Region {Name = "Banff National Park - North"},
                                  new Region {Name = "Kananaskis Country"}
                              };
            regions.ForEach(r => repository.Insert(r));

            // Seed Locations
            var locations = new List<Location>
                                {
                                    new Location
                                        {
                                            Name = "Bow Valley Parkway",
                                            Description = "Road from Banff to Lake Louise",
                                            Directions = "Turn left off main highway 2km north of Banff",
                                            Region = regions[0]
                                        },
                                    new Location {Name = "Banff Townsite area", Region = regions[0]},
                                    new Location
                                        {
                                            Name = "Bow Lake area",
                                            Description = "20 minutes north of Lake Louise on IceField Parkway",
                                            Region = regions[3]
                                        },
                                    new Location {Name = "Smith Dorrien Highway", Region = regions[4]}
                                };
            locations.ForEach(l => repository.Insert(l));

            // Seed Difficulty Levels
            var difficulties = new List<Difficulty>
                                   {
                                       new Difficulty {DifficultyType = "Easy"},
                                       new Difficulty {DifficultyType = "Moderate"},
                                       new Difficulty {DifficultyType = "Challenging"},
                                       new Difficulty {DifficultyType = "Difficult"}
                                   };
            difficulties.ForEach(d => repository.Insert(d));

            // Seed TrailType Levels
            var trailTypes = new List<TrailType>
                                 {
                                     new TrailType {TrailTypeName = "Land"},
                                     new TrailType {TrailTypeName = "Air"},
                                     new TrailType {TrailTypeName = "Water"}
                                 };
            trailTypes.ForEach(t => repository.Insert(t));

            // Seed TransportType Levels
            var transportTypes = new List<TransportType>
                                     {
                                         new TransportType {TransportTypeName = "Hike"},
                                         new TransportType {TransportTypeName = "Cycle"},
                                         new TransportType {TransportTypeName = "Canoe"},
                                         new TransportType {TransportTypeName = "Ski"},
                                         new TransportType {TransportTypeName = "Snowshoe"},
                                         new TransportType {TransportTypeName = "Aeroplane"}
                                     };
            transportTypes.ForEach(t => repository.Insert(t));

            // Seed Trails
            var trails = new List<Trail>
                             {
                                 new Trail
                                     {
                                         Name = "Johnstone Canyon",
                                         Description = "Johnstone Canyon",
                                         Distance = 4.8M,
                                         ElevationGain = 200,
                                         EstimatedTime = 2,
                                         Location = locations[0],
                                         TrailType = trailTypes[0],
                                         Difficulty = difficulties[0],
                                         ReturnOnEffort = 9.2M,
                                         OverallGrade = 7.2M,
                                         Notes =
                                             "Good Waterfalls scenery. Good in all seasons. Take crampons in winter/spring",
                                         Longitude = -102,
                                         Latitude = 50
                                     },
                                 new Trail
                                     {
                                         Name = "Burstall Pass",
                                         Description = "Burstall Pass",
                                         Distance = 8.53M,
                                         ElevationGain = 390,
                                         EstimatedTime = 4,
                                         Location = locations[1],
                                         TrailType = trailTypes[0],
                                         Difficulty = difficulties[0],
                                         ReturnOnEffort = 8.1M,
                                         OverallGrade = 8.1M,
                                         Notes = "Excellent view from the pass"
                                     },
                                 new Trail
                                     {
                                         Name = "Helen Lake",
                                         Description = "Helen Lake",
                                         Distance = 8M,
                                         ElevationGain = 480,
                                         EstimatedTime = 4.5M,
                                         Location = locations[2],
                                         TrailType = trailTypes[0],
                                         Difficulty = difficulties[3],
                                         ReturnOnEffort = 7.8M,
                                         OverallGrade = 7.8M,
                                         Notes = "Views across to the Dolomite range."
                                     },
                                 new Trail
                                     {
                                         Name = "Chester Lake",
                                         Description = "Chester Lake",
                                         Distance = 8.11M,
                                         ElevationGain = 520,
                                         EstimatedTime = 4.5M,
                                         Location = locations[2],
                                         TrailType = trailTypes[0],
                                         Difficulty = difficulties[1],
                                         ReturnOnEffort = 6.9M,
                                         OverallGrade = 6.9M,
                                         Notes = "Don't stop at Chester Lake - go on to Three Lake Valley"
                                     }
                             };

            trails.ForEach(t => repository.Insert(t));

            // Seed Trips
            var trips = new List<Trip>
                            {
                                new Trip
                                    {
                                        Date = new DateTime(2001, 9, 1),
                                        TransportType = transportTypes[0],
                                        Trail = trails[0],
                                        Weather = "Cloudy",
                                        TimeTaken = 3.3M,
                                        Notes = "Very slippery - cramps needed.",
                                        Persons = new List<Person>
                                        {
                                            persons[0], persons[1],persons[2]
                                        }
                                    },
                                new Trip
                                    {
                                        Date = new DateTime(2004, 7, 31),
                                        TransportType = transportTypes[1],
                                        Trail = trails[0],
                                        Weather = "Sunny",
                                        TimeTaken = 2.3M,
                                        Notes = "First time on this trail."

                                    }
                            };
            trips.ForEach(t => repository.Insert(t));

            repository.SaveChanges();
        }
Exemplo n.º 52
0
        public void MyTestInitialize()
        {
            ObjectContext edmContext = new DemoEntities();
            _repository = EDMRepositoryContext.GetCurrentContext(edmContext).GetRepository<SysParam>();
            //清理垃圾数据
            var rubbish = _repository.GetFilteredElements(x => x.sysparamName.StartsWith("ParamName"));
            if (rubbish == null || rubbish.Count() <= 0) return;
            foreach (var item in rubbish)
                this._repository.Remove(item);

            _repository.SaveChanges();
        }
Exemplo n.º 53
0
 public void Update(BusinessObjects.Model entity)
 {
     using (_ModelRepository = new GenericRepository<DAL.DataEntities.Model>())
     {
         entity.LastModifiedDate = DateTime.Now;
         //
         _ModelRepository.Attach((DAL.DataEntities.Model)entity.InnerEntity);
         _ModelRepository.SaveChanges();
     }
 }
Exemplo n.º 54
0
 public void Delete(int id)
 {
     DAL.DataEntities.Relation relation;
     using (_RelationRepository = new GenericRepository<DAL.DataEntities.Relation>())
     {
         relation = _RelationRepository.SingleOrDefault(m => m.ID == id);
         _RelationRepository.Delete(relation);
         _RelationRepository.SaveChanges();
     }
 }
        public void UpdateName(int configurationID, string newName)
        {
            using (_ConfigurationRepository = new GenericRepository<DAL.DataEntities.Configuration>())
            {
                DAL.DataEntities.Configuration model = _ConfigurationRepository.SingleOrDefault(m => m.ID == configurationID);
                model.LastModifiedDate = DateTime.Now;
                model.Name = newName;

                _ConfigurationRepository.SaveChanges();
            }
        }
Exemplo n.º 56
0
 public void Delete(int id)
 {
     DAL.DataEntities.Attribute attribute;
     using (_AttributeRepository = new GenericRepository<DAL.DataEntities.Attribute>())
     {
         attribute = _AttributeRepository.SingleOrDefault(m => m.ID == id);
         _AttributeRepository.Delete(attribute);
         _AttributeRepository.SaveChanges();
     }
 }
Exemplo n.º 57
0
        private static void ClearDatabase(IRepository<News> repository)
        {
            foreach (var news in repository.All())
            {
                repository.Delete(news.Id);
            }

            repository.SaveChanges();
        }
 public void Update(BusinessObjects.Configuration entity)
 {
     using (_ConfigurationRepository = new GenericRepository<DAL.DataEntities.Configuration>())
     {
         entity.LastModifiedDate = DateTime.Now;
         //
         _ConfigurationRepository.Attach((DAL.DataEntities.Configuration)entity.InnerEntity);
         _ConfigurationRepository.SaveChanges();
     }
 }
Exemplo n.º 59
0
 public void Delete(int id)
 {
     DAL.DataEntities.CustomRule customRule;
     using (_CustomRuleRepository = new GenericRepository<DAL.DataEntities.CustomRule>())
     {
         customRule = _CustomRuleRepository.SingleOrDefault(m => m.ID == id);
         _CustomRuleRepository.Delete(customRule);
         _CustomRuleRepository.SaveChanges();
     }
 }
Exemplo n.º 60
0
        private static void SeedNews(IRepository<News> repository)
        {
            var newsList = ListOfNews;

            foreach (var news in newsList)
            {
                repository.Add(news);
            }

            repository.SaveChanges();
        }