Пример #1
0
 public void Eliminar(Empresa itemEliminar)
 {
     using (EFContext db = new EFContext(ConexionUtil.ObtenerCadena()))
     {
         Empresa empresa = (from s in db.Empresa
                                where s.Codigo == itemEliminar.Codigo
                                select s).Single();
         db.Empresa.Remove(empresa);
         db.SaveChanges();
     }
 }
Пример #2
0
 /// <summary>
 /// Crear Empresa
 /// </summary>
 /// <param name="EmpresaACrear">Dominio Empresa</param>
 /// <returns>Dominio Empresa</returns>
 public Empresa Crear(Empresa EmpresaACrear)
 {
     using (EFContext db = new EFContext(ConexionUtil.ObtenerCadena()))
     {
         int? codigo = db.Empresa.Select(l => (int?)l.Codigo).Max();
         EmpresaACrear.Codigo = (codigo ?? 0) + 1;
         db.Empresa.Add(EmpresaACrear);
         db.SaveChanges();
     }
     return Obtener(EmpresaACrear.Codigo);
 }
 /// <summary>
 /// Crear VentaPauta
 /// </summary>
 /// <param name="EmpresaACrear">Dominio VentaPauta</param>
 /// <returns>Dominio VentaPauta</returns>
 public VentaPauta Crear(VentaPauta VentaPautaACrear)
 {
     using (EFContext db = new EFContext(ConexionUtil.ObtenerCadena()))
     {
         int? codigo = db.VentaPauta.Select(l => (int?)l.Codigo).Max();
         VentaPautaACrear.Codigo = (codigo ?? 0) + 1;
         db.VentaPauta.Add(VentaPautaACrear);
         db.SaveChanges();
     }
     return Obtener(VentaPautaACrear.Codigo);
 }
Пример #4
0
 public IActionResult Create(string Name, string Type, string Tel, string Web, string Adress, string District, string City)
 {
     if (Name != null && Type != null && Tel != null && Adress != null)
     {
         try
         {
             c.Restaurants.Add(
                 new Restaurant
             {
                 Name         = Name,
                 Type         = Type,
                 Web          = Web,
                 Tel          = Tel,
                 District     = District,
                 City         = City,
                 Adress       = Adress,
                 RestaurantID = Guid.NewGuid().ToString(),
                 StarCount    = 0,
                 CreatedByID  = _userManager.GetUserId(User),
                 PublishDate  = DateTime.Now,
                 IsAccepted   = false,
                 Deleted      = false
             });
             c.SaveChanges();
             return(View());
         }
         catch
         {
             ViewData["Error"] = "Bir şeyler ters gitti!. #30001";
             return(View());
         }
     }
     else
     {
         ViewData["Error"] = "Boş gönderemezsin #NULLERROR";
         return(View());
     }
 }
Пример #5
0
        public async Task ReIndex_when_no_issues_should_reIndexCosts()
        {
            //Setup
            const int costsCount = 2;

            var costs = new bool[costsCount].Select(i => new Cost
            {
                Created = DateTime.Now,
                Id      = Guid.NewGuid()
            }).ToList();

            _mapperMock.Setup(m => m.Map <List <CostSearchItem> >(It.IsAny <List <Cost> >()))
            .Returns(new bool[costsCount]
                     .Select(i => new CostSearchItem
            {
                Id      = Guid.NewGuid().ToString(),
                Version = 1
            }).ToList
                     );
            var costSearchItems = _mapperMock.Object.Map <List <CostSearchItem> >(costs);

            _efContext.Cost.AddRange(costs);
            _efContext.SaveChanges();

            _costSearchBuilderMock.Setup(a => a.GetCostSearchItems(It.IsAny <List <Guid> >()))
            .ReturnsAsync(costSearchItems);

            _elasticBultResponseMock.Setup(r => r.IsValid).Returns(true);
            _elasticClientMock.Setup(a => a.BulkAsync(It.IsAny <Func <BulkDescriptor, IBulkRequest> >(), CancellationToken.None))
            .ReturnsAsync(_elasticBultResponseMock.Object);

            _elasticClientMock.Setup(a => a.IndexExists(It.IsAny <string>(), null).Exists).Returns(true);

            SetupValidAliasResponses(Constants.ElasticSearchIndices.CostsIndexName);

            //Act
            var result = await _elasticSearchIndexService.ReIndex(Constants.ElasticSearchIndices.CostsIndexName);

            //Assert
            result.Error.Should().BeFalse();
            result.BootstrappedItems.Should().ContainKey(Constants.ElasticSearchIndices.CostsIndexName);
            result.BootstrappedItems[Constants.ElasticSearchIndices.CostsIndexName].Should().Be(costsCount);
        }
        public async Task SubmitCost_Set_ExchangeRateDate_On_OE_State()
        {
            // Arrange
            const decimal costExchangeRate = 0.35m;
            const decimal exchangeRate     = 0.25m;
            var           dateMin          = DateTime.UtcNow;
            var           cost             = new Cost
            {
                Id                      = Guid.NewGuid(),
                ExchangeRate            = costExchangeRate,
                ExchangeRateDate        = DateTime.UtcNow.AddDays(-1),
                LatestCostStageRevision = new CostStageRevision
                {
                    Name      = CostStages.OriginalEstimate.ToString(),
                    CostStage = new CostStage {
                        Key = CostStages.OriginalEstimate.ToString()
                    },
                    IsPaymentCurrencyLocked = false
                },
                PaymentCurrencyId = Guid.NewGuid()
            };

            EFContext.Cost.Add(cost);
            EFContext.SaveChanges();
            _exchangeRateServiceMock.Setup(er => er.GetCurrentRate(cost.PaymentCurrencyId.Value))
            .ReturnsAsync(new ExchangeRate {
                Rate = exchangeRate
            });

            // Act
            await CostBuilder.SubmitCost(cost.Id);

            // Assert
            cost.ExchangeRate.Should().Be(exchangeRate);
            cost.ExchangeRateDate.Should().HaveValue();
            cost.ExchangeRateDate.Should().BeAfter(dateMin);
            cost.ExchangeRateDate.Should().BeOnOrBefore(DateTime.UtcNow);
        }
Пример #7
0
 public void GravarAbastecimento(Abastecimento abastecimento)
 {
     using EFContext Context = new EFContext();
     if (abastecimento.AbastecimentoId == null)
     {
         Context.Abastecimentos.Add(abastecimento);
     }
     else
     {
         AttachItem(abastecimento, Context);
         Context.Entry(abastecimento).State = EntityState.Modified;
     }
     Context.SaveChanges();
 }
Пример #8
0
        private void SetupBusinessRoles()
        {
            var ipmBusinessRole = new BusinessRole()
            {
                Key   = "Integrated Production Manager",
                Value = "Integrated Production Manager",
            };
            var brandBusinessRole = new BusinessRole()
            {
                Key   = "Brand Manager",
                Value = "Brand Management Approver"
            };
            var agencyAdmin = new BusinessRole()
            {
                Key   = "Agency Admin",
                Value = "Agency Admin"
            };

            EFContext.BusinessRole.Add(ipmBusinessRole);
            EFContext.BusinessRole.Add(brandBusinessRole);
            EFContext.BusinessRole.Add(agencyAdmin);
            EFContext.SaveChanges();
        }
Пример #9
0
 public int SaveChanges()
 {
     try
     {
         // Transaction işlemleri burada ele alınabilir veya Identity Map kurumsal tasarım kalıbı kullanılarak
         // sadece değişen alanları güncellemeyide sağlayabiliriz.
         return(_dbContext.SaveChanges());
     }
     catch
     {
         // Burada DbEntityValidationException hatalarını handle edebiliriz.
         throw;
     }
 }
Пример #10
0
        public void GravarAparelho(Aparelho aparelho)
        {
            int idAparelho = aparelho.id;

            if (idAparelho == 0)//Perguntar para professor porque não pode comparar com NULL conforme o livro
            {
                context.Tbl_Aparelho.Add(aparelho);
            }
            else
            {
                context.Entry(aparelho).State = EntityState.Modified;
            }
            context.SaveChanges();
        }
Пример #11
0
        public async Task QueryEntries_When_MaxEntries_ShouldLimitResult()
        {
            // Arrange
            var dictionaryId         = Guid.NewGuid();
            var dictionaryEntryCount = 2;
            var maxEntries           = 1;
            var entries = new bool[dictionaryEntryCount].Select((i, j) => new DictionaryEntry
            {
                DictionaryId = dictionaryId,
                Key          = j.ToString(),
                Value        = j.ToString(),
                Visible      = true
            });

            _efContext.DictionaryEntry.AddRange(entries);
            _efContext.SaveChanges();

            // Act
            var result = await _dictionaryService.QueryEntries(dictionaryId, null, maxEntries);

            // Assert
            result.Should().HaveCount(maxEntries);
        }
Пример #12
0
        public ActionResult Edit(EditModel model)
        {
            if (ModelState.IsValid)
            {
                user           = context.User.SingleOrDefault(u => u.Email == User.Identity.Name);
                user.FirstName = model.FirstName;
                user.LastName  = model.LastName;
                //user.Password = model.Password;
                context.SaveChanges();

                return(RedirectToAction("Profile"));
            }
            return(RedirectToAction("Index", "Home"));
        }
Пример #13
0
 public ActionResult Create(string cnpj, [Bind(Include = "idEmpresa,cnpj,nome,dataAbertura,atividade")] Empresa empresa)
 {
     if (ModelState.IsValid)
     {
         var consempresa = from s in db.Empresas
                           select s;
         if (!String.IsNullOrEmpty(cnpj))
         {
             consempresa = consempresa.Where(s => s.cnpj == (cnpj));
             if (consempresa.Count() == 0)
             {
                 db.Empresas.Add(empresa);
                 db.SaveChanges();
                 ViewBag.message = "Empresa cadastrada com sucesso";
             }
             else
             {
                 ViewBag.message = "Erro! Empresa ja cadastrada";
             }
         }
     }
     return(View(empresa));
 }
Пример #14
0
 public Empresa Modificar(Empresa itemAModificar)
 {
     using (EFContext db = new EFContext(ConexionUtil.ObtenerCadena()))
     {
         Empresa empresa = db.Empresa.Single(l => l.Codigo == itemAModificar.Codigo);
         empresa.RUC = itemAModificar.RUC;
         empresa.nombrecomercial = itemAModificar.nombrecomercial;
         empresa.direccion = itemAModificar.direccion;
         empresa.telefono = itemAModificar.telefono;
         empresa.Estado = itemAModificar.Estado;
         db.SaveChanges();
         return empresa;
     }
 }
        public ActionResult Create([Bind(Include = "FilmeId,Nome,Ano,DiretorId")] Filme filme, string[] selectedGeneros)
        {
            if (selectedGeneros != null)
            {
                filme.Generos = new List <Genero>();
                foreach (var item in selectedGeneros)
                {
                    var generoToAdd = db.Generos.Find(int.Parse(item));
                    filme.Generos.Add(generoToAdd);
                }
            }

            if (ModelState.IsValid)
            {
                db.Filmes.Add(filme);
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }
            PopulateGeneroData(filme);

            ViewBag.DiretorId = new SelectList(db.Diretores, "DiretorId", "Nome", filme.DiretorId);
            return(View(filme));
        }
Пример #16
0
        public ResultDTO AddDiscussion([FromBody] DiscussionDTO model)
        {
            var question = new Discussion
            {
                QuestionText = model.QuestionText
            };

            question.Options = model.Options.Select(x => new Options
            {
                Discussion = question,
                Counter    = x.Counter,
                Value      = x.Value
            }).ToList();

            _context.Discussions.Add(question);
            _context.SaveChanges();

            return(new ResultDTO
            {
                Message = "OK",
                Status = 200
            });
        }
Пример #17
0
 public ActionResult Create(CountryCreateViewModel model)
 {
     if (ModelState.IsValid)
     {
         Country isFind = _context.Countries.SingleOrDefault(x => x.Name == model.Name);
         if (isFind != null)
         {
             ModelState.AddModelError("", "Дві країни з однаковою назвою...Знову щось пішло не так)))");
             return(View(model));
         }
         Country country = new Country
         {
             DateCreate = DateTime.Now,
             Name       = model.Name,
             Priority   = model.Priority
         };
         _context.Countries.Add(country);
         _context.SaveChanges();
         return(RedirectToAction("Index"));
     }
     ModelState.AddModelError("", "Дружок не тупи");
     return(View(model));
 }
Пример #18
0
        public void UploadAccountImageIfNotExists(DbUser user, string imagePath)
        {
            string   name     = user.AvatarUrl;
            string   filePath = Path.Combine(_fileDestDir, name);
            FileInfo fileInf  = new FileInfo(filePath);

            if (!fileInf.Exists)
            {
                string pathPicture = UploadAccountImage(imagePath);
                user.AvatarUrl = pathPicture;
                _context.Users.Update(user);
                _context.SaveChanges();
            }
        }
Пример #19
0
        public void EFContext_Can_CRUD_Book_FluentAssertions()
        {
            Book b1 = new Book {
                Author = "Michael Zöhling", Title = "Unittests leicht gemacht", ISBN = "abcasdksadlk123123", BasePrice = 9.99m, Pages = 200
            };
            string newTitle = "Unittests schwer gemacht :)";

            // Create
            using (EFContext context = new EFContext(connectionString))
            {
                context.Book.Add(b1);
                context.SaveChanges();
            }

            // Check für Create / Read
            using (EFContext context = new EFContext(connectionString))
            {
                var loadedBook = context.Book.Find(b1.ID);
                // Assert.AreEqual(b1.ISBN, loadedBook.ISBN); // Richtige Vorgehensweise: Graphen-Vergleich

                // loadedBook.ISBN.Should().Be(b1.ISBN);
                // Graph:
                loadedBook.Should().BeEquivalentTo(b1);

                // Update
                loadedBook.Title = newTitle;
                context.SaveChanges();
            }

            // Check für Update
            using (EFContext context = new EFContext(connectionString))
            {
                var loadedBook = context.Book.Find(b1.ID);

                //Assert.AreEqual(newTitle, loadedBook.Title);
                loadedBook.Title.Should().Be(newTitle);

                // Delete
                context.Book.Remove(loadedBook);
                context.SaveChanges();
            }

            // Check für Delete
            using (EFContext context = new EFContext(connectionString))
            {
                var loadedBook = context.Book.Find(b1.ID);
                // Assert.IsNull(loadedBook);
                loadedBook.Should().BeNull();
            }
        }
Пример #20
0
 static void Main(string[] args)
 {
     using (EFContext context = new EFContext())
     {
         UserProfile aslan = new UserProfile {
             Name      = "Aslan",
             Image     = "img.jpg",
             Telephone = "+3454635464654"
         };
         context.UserProfiles.Add(aslan);
         context.SaveChanges();
         Console.WriteLine($"UserProfiles ID = {aslan.Id}");
     }
 }
        private void UpdateStand(Stand stand)
        {
            var standToUpdate = _dbContext.Stands.FirstOrDefault(c => c.Id == stand.Id);

            if (standToUpdate == null)
            {
                _dbContext.Stands.Add(stand);
            }
            else
            {
                _dbContext.Entry(standToUpdate).CurrentValues.SetValues(stand);
            }
            _dbContext.SaveChanges();
        }
Пример #22
0
 public ContentResult DeleteProduct(int id)
 {
     try
     {
         var product = context.Dbproduct.FirstOrDefault(w => w.Id == id);
         context.Remove(product);
         context.SaveChanges();
         return(Content("Product successfuly deleted"));
     }
     catch (Exception ex)
     {
         return(Content("Error" + ex.Message));
     }
 }
 /// <summary>
 /// Insere ou atualiza dados do produto atual.
 /// </summary>
 private void InsertOrUpdateProduct()
 {
     //Verifica se todos os campos obrigatórios estão preenchidos.
     if ((currentProduct.name != null && selectedProvider != null) && (currentProduct.name != "" && selectedProvider != ""))
     {
         //Insere um novo Produto
         if (currentProduct.id == 0)
         {
             DataTable providerFounded = ADOHelper.QueryProvidersByName(mainWindowContext.connectionString, selectedProvider);
             currentProduct.provider_id = (int)providerFounded.Rows[0][0];
             DataTable productFounded = ADOHelper.QueryProductsByName(mainWindowContext.connectionString, currentProduct.name, "=");
             if (productFounded.Rows.Count == 0)
             {
                 EFContext.products.Add(currentProduct);
                 EFContext.SaveChanges();
                 RefreshEFContext();
                 productFounded    = ADOHelper.QueryProductsByName(mainWindowContext.connectionString, currentProduct.name);
                 currentProduct.id = (int)productFounded.Rows[0][0];
                 ResetProductFields();
                 ButtonsHandler();
                 SearchProduct();
                 isRegisterTabFocused = false;
                 isQueryTabFocused    = true;
             }
             else
             {
                 msgBox = new AlphaMessageBox(mainWindowContext.productWindow, "Já existe um produto com este nome.");
                 msgBox.ShowDialog();
             }
         }
         else
         {
             product   oldProduct      = EFContext.products.Find(currentProduct.id);
             DataTable providerFounded = ADOHelper.QueryProvidersByName(mainWindowContext.connectionString, selectedProvider, "", "=");
             currentProduct.provider_id = (int)providerFounded.Rows[0][0];
             UpdateProduct(oldProduct);
             EFContext.SaveChanges();
             ResetProductFields();
             ButtonsHandler();
             SearchProduct();
             isRegisterTabFocused = false;
             isQueryTabFocused    = true;
         }
     }
     else
     {
         msgBox = new AlphaMessageBox(mainWindowContext.productWindow, "Preencha os campos obrigatórios.");
         msgBox.ShowDialog();
     }
 }
        public ActionResult Create(CityCreateViewModel model)
        {
            City city = new City
            {
                Name       = model.Name,
                DateCreate = DateTime.Now,
                Priority   = model.Priority,
                CountryId  = model.CountryId
            };

            _context.Cities.Add(city);
            _context.SaveChanges();
            return(RedirectToAction("Index"));
        }
Пример #25
0
        public ActionResult Create(CreateGameViewModel model)
        {
            _context.Games.Add(new Games {
                Name        = model.Name,
                DateRelease = model.DateRelease,
                URL_Image   = model.URL_Image,
                Developer   = model.Developer,
                Price       = model.Price,
                Description = model.Description
            });
            _context.SaveChanges();

            return(RedirectToAction("Index", "Game"));
        }
Пример #26
0
 public VentaPauta Modificar(VentaPauta itemAModificar)
 {
     using (EFContext db = new EFContext(ConexionUtil.ObtenerCadena()))
     {
         VentaPauta ventapauta = db.VentaPauta.Single(l => l.Codigo == itemAModificar.Codigo);
         ventapauta.Codigo = itemAModificar.Codigo;
         ventapauta.ventaEstado = itemAModificar.ventaEstado;
         ventapauta.ventaUsuarioModif = itemAModificar.ventaUsuarioModif;
         ventapauta.ventaFechaModif = itemAModificar.ventaFechaModif;
         ventapauta.ventaEstado = itemAModificar.ventaEstado;
         db.SaveChanges();
         return ventapauta;
     }
 }
Пример #27
0
        /// <summary>
        /// Delete data from the specified ID collection (batch deletion)
        /// </summary>
        /// <param name="ids">primary key ID set </param>
        /// <returns></returns>
        public bool DeleteByIds(object[] ids)
        {
            int i = 0;

            using (EFContext context = new EFContext())
            {
                foreach (int item in ids)
                {
                    i = context.Posts.Remove(context.Posts.FirstOrDefault(t => t.Id == item)).Id;
                }
                context.SaveChanges();
                return(i > 0);
            }
        }
Пример #28
0
        private static void UpdateProduct()
        {
            // Create a new instance of the DbContext class.
            using EFContext db = new EFContext();
            Product product = db.Products.Find(1);

            product.Name = "Better Pen Drive";

            product      = db.Products.Find(2);
            product.Name = "Better Memory Card";

            db.SaveChanges();
            return;
        }
Пример #29
0
        static void AddDataToDB()
        {
            using (var db = new EFContext())
            {
                if (db.Outdoors.Any())
                {
                    //Console.Write("Db already exists!");
                    return;
                }
            }

            List <Indoor>  indoorList  = new List <Indoor>();
            List <Outdoor> outdoorList = new List <Outdoor>();

            using (var reader = new StreamReader("Data\\TemperaturData.csv"))
            {
                var provider = new CultureInfo("en-US");

                while (!reader.EndOfStream)
                {
                    var line   = reader.ReadLine();
                    var values = line.Split(',');
                    if (values[1] == "Inne")
                    {
                        var indoorData = new Indoor();
                        indoorData.Date        = DateTime.Parse(values[0]);
                        indoorData.Temperature = double.Parse(values[2], provider);
                        indoorData.Humidity    = int.Parse(values[3]);
                        indoorList.Add(indoorData);
                    }
                    else
                    {
                        var outdoorData = new Outdoor();
                        outdoorData.Date        = DateTime.Parse(values[0]);
                        outdoorData.Temperature = double.Parse(values[2], provider);
                        outdoorData.Humidity    = int.Parse(values[3]);
                        outdoorList.Add(outdoorData);
                    }
                }
            }

            using (var db = new EFContext())
            {
                Console.Write("Working...");
                db.Indoors.AddRange(indoorList);
                db.Outdoors.AddRange(outdoorList);
                db.SaveChanges();
                Console.WriteLine("Finished.");
            }
        }
Пример #30
0
        public void deleteStudent(int id)
        {
            var db = new EFContext();

            try
            {
                db.Students.Remove(db.Students.Single(t => t.StudentId == id));
                db.SaveChanges();
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
        }
Пример #31
0
        public void EFContext_can_CRUD_Person_FluentAssertions_Autofixture()
        {
            Fixture fix        = new Fixture();
            Person  p1         = fix.Create <Person>();
            string  newVorname = fix.Create <string>();

            // Create
            using (EFContext context = new EFContext(connectionString))
            {
                context.Person.Add(p1); // SQL-Insert
                context.SaveChanges();
            }

            // Check Create
            using (EFContext context = new EFContext(connectionString))
            {
                Person loadedPerson = context.Person.Find(p1.ID);
                // Check: Read
                // Assert.IsTrue(loadedPerson.Vorname == p1.Vorname); // ToDo: Richtig: ObjectGraph

                //loadedPerson.Vorname.Should().Be(p1.Vorname);

                //ObjectGraph:
                loadedPerson.Should().BeEquivalentTo(p1); // Vergleicht alle Properties

                // Update
                loadedPerson.Vorname = newVorname; //EF: Changetracker
                context.SaveChanges();
            }

            // Check Update
            using (EFContext context = new EFContext(connectionString))
            {
                Person loadedPerson = context.Person.Find(p1.ID);
                // Check: Read
                loadedPerson.Vorname.Should().Be(newVorname);


                // Delete
                context.Person.Remove(loadedPerson);
                context.SaveChanges();
            }

            // Check Delete
            using (EFContext context = new EFContext(connectionString))
            {
                Person loadedPerson = context.Person.Find(p1.ID);
                loadedPerson.Should().BeNull();
            }
        }
Пример #32
0
 private void btnAddUser_Click(object sender, RoutedEventArgs e)
 {
     try
     {
         AddUser addUser = new AddUser();
         addUser.ShowDialog();
         users.Add(new UserModel()
         {
             Name = addUser.AddName
         });
         _context.UsersDB.Add(new User()
         {
             Name = users.Where(u => u.Id == 0).First().Name
         });
         _context.SaveChanges();
     }
     catch
     {
         MessageBox.Show("adding errors");
     }
     MessageBox.Show($"add user(s)");
     DG_Load();
 }
Пример #33
0
        public void AddStudent(Student student)
        {
            var db = new EFContext();

            db.Students.Add(new Student()
            {
                StudentName = student.StudentName,
                Mobile      = student.Mobile,
                Course      = student.Course,
                Emaiol      = student.Emaiol,
                Fee         = student.Fee
            });
            db.SaveChanges();
        }
        public void EFContext_Can_CRUD_Person_Autofix_Fluent()
        {
            var fix = new Fixture();

            // Zyklisch oder rekursive Verweise:
            // fix.Behaviors.Add(new OmitOnRecursionBehavior());

            // fix.Create<Person>(); // --> Einzelne Person
            // fix.CreateMany<Person>(); // --> Mehrere Personen

            var    p           = fix.Create <Person>();
            string newLastName = "Atinger";

            // Test: Create
            using (var context = new EFContext(connectionString))
            {
                context.Person.Add(p); // Insert
                context.SaveChanges();
            }
            // Check für Create
            using (var context = new EFContext(connectionString))
            {
                var loadedPerson = context.Person.Find(p.ID);
                loadedPerson.Should().NotBeNull();       // Assert.NotNull(loadedPerson);
                loadedPerson.Should().BeEquivalentTo(p); // ObjectGraph-Vergleich

                // Update
                loadedPerson.LastName = newLastName;
                context.SaveChanges();
            }

            // Check für Update
            using (var context = new EFContext(connectionString))
            {
                var loadedPerson = context.Person.Find(p.ID);
                loadedPerson.Should().NotBeNull();
                loadedPerson.LastName.Should().Be(newLastName);

                // Delete
                context.Person.Remove(loadedPerson);
                context.SaveChanges();
            }

            // Check für Delete
            using (var context = new EFContext(connectionString))
            {
                var loadedPerson = context.Person.Find(p.ID);
                loadedPerson.Should().BeNull();
            }
        }
Пример #35
0
 /// <summary>
 /// Logout user
 /// </summary>
 /// <param name="userId"></param>
 public void Logout(int userId)
 {
     using (var db = new EFContext())
     {
         var user = db.Users?.FirstOrDefault(u => u.Id == userId);
         if (user != null)
         {
             user.SessionTimer = DateTime.MinValue;
             db.Update(user);
             db.SaveChanges();
             Startup.sessionCookie = user;
         }
     }
 }
Пример #36
0
        public void CustomerOrderTest()
        {
            System.Data.Entity.Database.SetInitializer<EFContext>(new CreateDatabaseIfNotExists<EFContext>());
            using (var context = new EFContext())
            {
                context.Database.CreateIfNotExists();
                Customer customer = new Customer
                {
                    Name = "Raviendra",
                    Email = "*****@*****.**",

                };
                context.Entry(customer).State = (EntityState) System.Data.EntityState.Added;
                context.SaveChanges();
            }
        }
Пример #37
0
        public void TestInitialize()
        {
            initializingDate = DateTime.UtcNow;

            EFContext.ClearDatabase();

            var context = new EFContext();

            admin = new Admin() { Data = "data", CreatedOn = initializingDate, LastUpdateOn = initializingDate };
            context.Admins.Add(admin);

            office1 = new Office() { Data = "data", Admin = admin, CreatedOn = initializingDate, LastUpdateOn = initializingDate };
            office2 = new Office() { Data = "data", Admin = admin, CreatedOn = initializingDate, LastUpdateOn = initializingDate };
            context.Offices.Add(office1);
            context.Offices.Add(office2);

            car1 = new Car() { Data = "data", Admin = admin, CreatedOn = initializingDate, LastUpdateOn = initializingDate };
            car2 = new Car() { Data = "data", Admin = admin, CreatedOn = initializingDate, LastUpdateOn = initializingDate };
            context.Cars.Add(car1);
            context.Cars.Add(car2);

            project1 = new Project() { Data = "data", Admin = admin, CreatedOn = initializingDate, LastUpdateOn = initializingDate };
            project2 = new Project() { Data = "data", Admin = admin, CreatedOn = initializingDate, LastUpdateOn = initializingDate };
            context.Projects.Add(project1);
            context.Projects.Add(project2);

            director = new Director() { Data = "data", CreatedOn = initializingDate, LastUpdateOn = initializingDate };
            context.Directors.Add(director);

            directorTracker = new DirectorTracker()
            {
                Data = "data",
                Director = director,
                CreatedOn = initializingDate,
                LastUpdateOn = initializingDate
            };
            context.DirectorTrackers.Add(directorTracker);

            context.SaveChanges();
        }
Пример #38
0
        public void Get_WithUsingEntities_IsUsedIsTrue()
        {
            //Arrange
            var repository = new EFRepositoryTester();
            repository.Initialize();

            var manager = new Manager()
            {
                Director = director,
                ManagerTrackers = new List<ManagerTracker>()
                {
                    new ManagerTracker()
                },
                Office = office1,
                Computer = new Computer() { Data = "data", Admin = admin },
                Things = new List<Thing>()
                {
                    new Thing()
                    {
                        Id = 1,
                        Admin = admin,
                        Data = "data"
                    },
                    new Thing()
                    {
                        Id = 2,
                        Admin = admin,
                        Data = "data"
                    }
                },
                Description = new Description()
                {
                    Data = "data"
                },
                Data = "data",
                Car = car1,
                Projects = new List<Project>()
                {
                    project1,
                    //project2
                }
            };

            repository.Add(new AddOperationParameters<Manager>()
            {
                Entity = manager,
                OperationDateTime = initializingDate
            });

            //Attach using entities
            var context = new EFContext();

            context.Directors.Attach(director);
            context.Managers.Attach(manager);
            director.Managers = new List<Manager>();
            director.Managers.Add(manager);

            context.ManagerTrackers.Add(new ManagerTracker()
            {
                Manager = manager,
                Data = "data"
            });

            context.SaveChanges();

            //Act
            var entities = repository.Get(new GetOperationParameters()
            {
                LoadSubEntities = true,
                LoadUsedEntities = true,
                LoadUsingEntities = true,
            });

            //Assert
            Assert.AreEqual(true, entities[0].IsUsed);
        }
Пример #39
0
        public void Get_WithAllRelatedEntities_ReturnsEntities()
        {
            //Arrange
            var repository = new EFRepositoryTester();
            repository.Initialize();

            var manager = new Manager()
            {
                Director = director,
                ManagerTrackers = new List<ManagerTracker>()
                {
                    new ManagerTracker()
                },
                Office = office1,
                Computer = new Computer() { Data = "data", Admin = admin },
                Things = new List<Thing>()
                {
                    new Thing()
                    {
                        Id = 1,
                        Admin = admin,
                        Data = "data"
                    },
                    new Thing()
                    {
                        Id = 2,
                        Admin = admin,
                        Data = "data"
                    }
                },
                Description = new Description()
                {
                    Data = "data"
                },
                Data = "data",
                Car = car1,
                Projects = new List<Project>()
                {
                    project1,
                    //project2
                }
            };

            repository.Add(new AddOperationParameters<Manager>()
            {
                Entity = manager,
                OperationDateTime = initializingDate
            });

            //Attach using entities
            var context = new EFContext();

            context.Directors.Attach(director);
            context.Managers.Attach(manager);
            director.Managers = new List<Manager>();
            director.Managers.Add(manager);

            context.ManagerTrackers.Add(new ManagerTracker()
            {
                Manager = manager,
                Data = "data"
            });

            context.SaveChanges();

            //Act
            var entities = repository.Get(new GetOperationParameters()
            {
                LoadSubEntities = true,
                LoadUsedEntities = true,
                LoadUsingEntities = true,
            });

            //Assert
            Assert.AreEqual(true, entities[0].IsUsed);

            AssertUsingEntities();

            AssertSecondLevelUsedEntities();

            //Sub entities
            Assert.AreEqual(1, entities.Length);
            Assert.AreEqual("data", entities[0].Computer.Data);
            Assert.AreEqual(admin.Id, entities[0].Computer.Admin.Id);

            Assert.AreEqual("data", entities[0].Description.Data);

            Assert.AreEqual("data", entities[0].Things[0].Data);
            Assert.AreEqual(admin.Id, entities[0].Things[0].Admin.Id);
            Assert.AreEqual(entities[0].Id, entities[0].Things[0].Manager.Id);

            Assert.AreEqual("data", entities[0].Things[1].Data);
            Assert.AreEqual(admin.Id, entities[0].Things[1].Admin.Id);
            Assert.AreEqual(entities[0].Id, entities[0].Things[1].Manager.Id);

            //Main entity
            Assert.AreEqual("data", entities[0].Data);
            Assert.AreEqual(car1.Id, entities[0].Car.Id);
            Assert.AreEqual(director.Id, entities[0].Director.Id);
            Assert.AreEqual(office1.Id, entities[0].Office.Id);

            //First level used entities
            Assert.AreEqual(office1.Id, entities[0].Office.Id);
            Assert.AreEqual("data", entities[0].Office.Data);

            Assert.AreEqual(admin.Id, entities[0].Car.Admin.Id);
            Assert.AreEqual(car1.Id, entities[0].Car.Id);
            Assert.AreEqual("data", entities[0].Car.Data);

            Assert.AreEqual(admin.Id, entities[0].Projects[0].Admin.Id);
            Assert.AreEqual(project1.Id, entities[0].Projects[0].Id);
            Assert.AreEqual("data", entities[0].Projects[0].Data);
            Assert.AreEqual(manager.Id, entities[0].Projects[0].Manager.Id);

            //Assert.AreEqual(admin.Id, entities[0].Projects[1].AdminId);
            //Assert.AreEqual(project2.Id, entities[0].Projects[1].Id);
            //Assert.AreEqual(initializingDate, entities[0].Projects[1].CreatedOn);
            //Assert.AreEqual(initializingDate, entities[0].Projects[1].LastUpdateOn);
            //Assert.AreEqual("data", entities[0].Projects[1].Data);
            //Assert.AreEqual(false, entities[0].Projects[1].IsDeleted);
            //Assert.AreEqual(manager.Id, entities[0].Projects[1].ManagerId);

            //Using entities
            Assert.AreEqual("data", entities[0].ManagerTrackers[0].Data);
            Assert.AreEqual(manager.Id, entities[0].ManagerTrackers[0].Manager.Id);

            //Get result
        }
Пример #40
0
        /// <summary>
        /// The EF code first.
        /// </summary>
        /// <returns>the entity framework code first view.</returns>
        public ActionResult EFCodeFirst()
        {
            int count;
            int? newCount = null;

            EFContext context = null;
            using (MiniProfiler.Current.Step("EF Stuff"))
            {
                try
                {
                    using (MiniProfiler.Current.Step("Create Context"))
                        context = new EFContext();

                    // this is not correct, as the count from this assignment is never actually used
                    using (MiniProfiler.Current.Step("First count"))
                        count = context.People.Count();

                    using (MiniProfiler.Current.Step("Insertion"))
                    {
                        var p = new Person { Name = "sam" };
                        context.People.Add(p);
                        context.SaveChanges();
                    }

                    // this count is actually used.
                    using (MiniProfiler.Current.Step("Second count"))
                        count = context.People.Count();

                    const string sql = "Select count(*) from People";
                    using (MiniProfiler.Current.Step("Get Count from SqlQuery Method - no sql recorded"))
                    {
                        newCount = context.Database.SqlQuery<int>(sql).Single();
                    }
                    using (MiniProfiler.Current.Step("Get Count using ProfiledConnection - sql recorded"))
                    {
                        using (var conn = new ProfiledDbConnection(context.Database.Connection, MiniProfiler.Current))
                        {
                            conn.Open();
                            newCount = conn.Query<int>(sql).Single();
                            conn.Close();
                        }
                    }

                }
                finally
                {
                    if (context != null)
                    {
                        context.Dispose();
                    }
                }
            }

            return Content(string.Format("EF Code First complete - count: {0}, sqlQuery count {1}", count, newCount));
        }
Пример #41
0
        /// <summary>
        /// The EF code first.
        /// </summary>
        /// <returns>the entity framework code first view.</returns>
        public ActionResult EFCodeFirst()
        {
            int count;

            EFContext context = null;
            using (MiniProfiler.Current.Step("EF Stuff"))
            {
                try
                {
                    using (MiniProfiler.Current.Step("Create Context"))
                        context = new EFContext();

                    // this is not correct, as the count from this assignment is never actually used
                    using (MiniProfiler.Current.Step("First count"))
                        count = context.People.Count();

                    using (MiniProfiler.Current.Step("Insertion"))
                    {
                        var p = new Person { Name = "sam" };
                        context.People.Add(p);
                        context.SaveChanges();
                    }

                    // this count is actually used.
                    using (MiniProfiler.Current.Step("Second count"))
                        count = context.People.Count();
                }
                finally
                {
                    if (context != null)
                    {
                        context.Dispose();
                    }
                }
            }

            return Content("EF Code First complete - count: " + count);
        }