public T Single(Expression <Func <T, bool> > predicate)
 {
     using (VirtualStoreContext context = new VirtualStoreContext())
     {
         return(context.Set <T>().FirstOrDefault(predicate));
     }
 }
        public void RemoveEmployees(Territory territory, List <Employee> employees)
        {
            //validamos que haya algo que remover
            if (employees == null || employees.Count == 0)
            {
                return;
            }

            using (VirtualStoreContext context = new VirtualStoreContext())
            {
                //recuperamos el terrotorio y sus empleados
                //esto es necesario porque el objeto donde se debe remover tiene que estar dentro del contexto de EF
                Territory territorySel = context.Set <Territory>().Include("Employees").FirstOrDefault(x => x.TerritoryId == territory.TerritoryId);

                if (territory.Employees == null || territory.Employees.Count == 0)
                {
                    return;
                }

                employees.ForEach(x =>
                {
                    //localizamos al empleado dentro de la coleccion que se recupero anteriormente
                    Employee employeeRemove = territorySel.Employees.First(e => e.EmployeeId == x.EmployeeId);
                    //se remueve de la coleccion haciendo uso de la instancia
                    territorySel.Employees.Remove(employeeRemove);
                });

                context.SaveChanges();
            }
        }
 public List <T> Filter(Expression <Func <T, bool> > predicate)
 {
     using (VirtualStoreContext context = new VirtualStoreContext())
     {
         return((List <T>)context.Set <T>().Where(predicate).ToList());
     }
 }
        public void AddEmployees(Territory territory, List <Employee> employes)
        {
            using (VirtualStoreContext context = new VirtualStoreContext())
            {
                //marcamos el territorio para que no reciba cambios
                context.Entry(territory).State = EntityState.Unchanged;

                if (territory.Employees == null)
                {
                    territory.Employees = new List <Employee>();
                }

                //recorremos cada empleado que se quiera asociar
                employes.ForEach(x =>
                {
                    //el empleado tampoco debe recibir cambios
                    context.Entry(x).State = EntityState.Unchanged;
                    //asociamos a la colecion de empleados del territorio el nuevo item
                    //este si recibira cambios
                    territory.Employees.Add(x);
                });

                context.SaveChanges();
            }
        }
Example #5
0
 /// <summary>
 /// Retorna todos los empleados internos a la empresa
 /// </summary>
 /// <returns></returns>
 public List <EmployeeInternal> GetAllInternalType()
 {
     using (VirtualStoreContext context = new VirtualStoreContext())
     {
         return(context.Employee2s.OfType <EmployeeInternal>().ToList());
     }
 }
Example #6
0
 //El método GetById() podría haberse omitido ya que el mismo dato podría haberse recuperado
 //mediante la el método Single() que define el repositorio base, utilizando
 //Category category = new CategoryRepository().Simple(x => x.CategoryID == categoryId);
 public Category GetById(int categoryID)
 {
     using (VirtualStoreContext context = new VirtualStoreContext())
     {
         return(context.Set <Category>().FirstOrDefault(x => x.CategoryId == categoryID));
     }
 }
 public List <T> GetAll()
 {
     using (VirtualStoreContext context = new VirtualStoreContext())
     {
         return((List <T>)context.Set <T>().ToList());
     }
 }
Example #8
0
        public void GetCustomers_GroupedByCountryAndBirdDate()
        {
            using (VirtualStoreContext context = new VirtualStoreContext())
            {
                DateTime birdDate = DateTime.Now.AddYears(-25);

                //var customers = (from customer in context.Customers
                //                where customer.Residence.Country == "Peru"
                //                    && customer.BirdDate > birdDate
                //                    && customer.LastName.StartsWith("P")
                //                select customer).ToList();

                var customerArg = from customer in context.Customers
                                  where customer.Residence.Country == "Peru"
                                  select customer;

                var customersStartWithP = from customer in customerArg
                                          where customer.LastName.StartsWith("P")
                                          select customer;

                var customers = customersStartWithP.Where(x => x.BirdDate > birdDate).ToList();

                Assert.IsNotNull(customers);
                Assert.AreEqual(customers.Count(), 1);

                Assert.AreEqual(customers[0].LastName, customer1.LastName);
            }
        }
Example #9
0
 /// <summary>
 /// Recupera solo la entidad Extendida
 /// </summary>
 /// <param name="id"></param>
 /// <returns></returns>
 public EmployeeExtended GetExtendedById(int id)
 {
     using (VirtualStoreContext context = new VirtualStoreContext())
     {
         return(context.EmployeeExtendeds.FirstOrDefault(x => x.EmployeeId == id));
     }
 }
        public virtual void Create(T entity, List <Expression <Func <T, object> > > unchangeProp)
        {
            // se obtiene la lista de propiedades que deben marcarse con el estado Unchanged
            List <string> unchangelist = unchangeProp.Select(x => ((MemberExpression)x.Body).Member.Name).ToList();

            using (VirtualStoreContext context = new VirtualStoreContext())
            {
                context.Set <T>().Add(entity);

                if (unchangeProp != null)
                {
                    // se toma la instancia del objeto que esta asignada a la propiedad
                    // y se asigna el estodo Unchanged
                    foreach (string property in unchangelist)
                    {
                        PropertyInfo propertyInfo = typeof(T).GetProperty(property);
                        var          value        = propertyInfo.GetValue(entity, null);

                        context.Entry(value).State = EntityState.Unchanged;
                    }
                }

                context.SaveChanges();
            }
        }
Example #11
0
 public Product GetWithCategory(int productID)
 {
     using (VirtualStoreContext context = new VirtualStoreContext())
     {
         return(context.Set <Product>().Include("Category").FirstOrDefault(x => x.ProductID == productID));
     }
 }
Example #12
0
        public void Initialize()
        {
            Database.SetInitializer(new DropCreateDatabaseAlways <VirtualStoreContext>());

            using (VirtualStoreContext context = new VirtualStoreContext())
            {
                context.Customers.RemoveRange(context.Customers);

                customer1 = new Customer()
                {
                    FirstName = "Andres",
                    LastName  = "Perez",
                    BirdDate  = DateTime.Now.AddYears(-20),
                    Residence = new Address()
                    {
                        Country = "Peru",
                        City    = "Huancayo",
                        Street  = "Av Real",
                        Number  = 1300
                    },
                    Email = "*****@*****.**"
                };
                context.Customers.Add(customer1);

                customer2 = new Customer()
                {
                    FirstName = "Eduardo",
                    LastName  = "Quispe",
                    BirdDate  = DateTime.Now.AddYears(-24),
                    Residence = new Address()
                    {
                        Country = "Argentina",
                        City    = "Tambo",
                        Street  = "Av mariscal castilla",
                        Number  = 4522
                    },
                    Email = "*****@*****.**"
                };
                context.Customers.Add(customer2);

                customer3 = new Customer()
                {
                    FirstName = "Manuel",
                    LastName  = "Yupanqui",
                    BirdDate  = DateTime.Now.AddYears(-30),
                    Residence = new Address()
                    {
                        Country = "Argentina",
                        City    = "Chilca",
                        Street  = "Av Leoncio Prado",
                        Number  = 2500
                    },
                    Email = "*****@*****.**",
                };
                context.Customers.Add(customer3);

                context.SaveChanges();
            }
        }
Example #13
0
        public void ManyToMany()
        {
            Database.SetInitializer(new DropCreateDatabaseAlways <VirtualStoreContext>());
            using (VirtualStoreContext context = new VirtualStoreContext())
            {
                var genre1 = new Genre()
                {
                    Description = "Ciencia Ficción"
                };
                context.Genres.Add(genre1);
                var genre2 = new Genre()
                {
                    Description = "Fantasia"
                };
                context.Genres.Add(genre2);

                context.SaveChanges();

                var book1 = new Book()
                {
                    Title           = "El Silmarillon",
                    Description     = @"El Silmarillon cuenta la historia de ... bla bla bla",
                    Price           = 139,
                    ISBN            = 1452356565,
                    PublicationYear = 2002,
                    Stock           = 5,
                    Author          = "J. R. R. Tolkien",
                    Genre           = new List <Genre>()
                    {
                        genre1, genre2
                    }
                };

                context.Products.Add(book1);

                var book2 = new Book()
                {
                    Title           = "El Nombre del viento",
                    Description     = @"El Nombre del viento cuenta la historia de ... bla bla bla",
                    Price           = 319,
                    ISBN            = 1452121512,
                    PublicationYear = 2009,
                    Stock           = 10,
                    Author          = "Patrick",
                    Genre           = new List <Genre>()
                    {
                        genre1
                    }
                };

                context.Products.Add(book2);

                context.SaveChanges();

                var books = context.Products.OfType <Book>().ToList();

                Assert.IsNotNull(books);
            }
        }
 public void Create(T entity)
 {
     using (VirtualStoreContext context = new VirtualStoreContext())
     {
         context.Set <T>().Add(entity);
         context.SaveChanges();
     }
 }
 public void Delete(T entity)
 {
     using (VirtualStoreContext context = new VirtualStoreContext())
     {
         context.Entry(entity).State = EntityState.Deleted;
         context.SaveChanges();
     }
 }
Example #16
0
        //obtener el ultimo id para Herencia - Tabla por tipo concreto - Table per Concrete Type
        public int GetLastId()
        {
            using (VirtualStoreContext context = new VirtualStoreContext())
            {
                int?lastId = context.Employees.Max(x => (int?)x.EmployeeId);

                return(lastId.HasValue ? lastId.Value : 0);
            }
        }
        public void ObtenerCustomers()
        {
            using (VirtualStoreContext context = new VirtualStoreContext())
            {
                var customers = context.Customers.ToList();

                Assert.AreEqual(customers.Count, 0);
            }
        }
 public void Delete(Expression <Func <T, bool> > predicate)
 {
     using (VirtualStoreContext context = new VirtualStoreContext())
     {
         var entities = context.Set <T>().Where(predicate).ToList();
         entities.ForEach(x => context.Entry(x).State = EntityState.Deleted);
         context.SaveChanges();
     }
 }
Example #19
0
        /// <summary>
        /// Retorna todos los empleados externos a la empresa
        /// con linq
        /// </summary>
        /// <returns></returns>
        public List <Employee2> GetAllExternalType()
        {
            using (VirtualStoreContext context = new VirtualStoreContext())
            {
                var result = from employee in context.Employee2s
                             where employee is EmployeeExternal
                             select employee;

                return(result.ToList());
            }
        }
Example #20
0
        public static void CreateDb()
        {
            using (VirtualStoreContext context = new VirtualStoreContext())
            {
                if (context.Database.Exists())
                {
                    context.Database.Delete();
                }

                context.Database.Create();
            }
        }
Example #21
0
        public void GetById()
        {
            using (VirtualStoreContext context = new VirtualStoreContext())
            {
                var customers = context.Customers.FirstOrDefault(c => c.CustomerId == customer1.CustomerId);

                Assert.IsNotNull(customers);

                Assert.AreEqual(customers.FirstName, customer1.FirstName);
                Assert.AreEqual(customers.LastName, customer1.LastName);
            }
        }
Example #22
0
 public void LazyLoadTest()
 {
     LlenarDatos();
     //Hace q se pueda acceder los datos internos del objeto segun  la demanda que se quiera, osea una busqueda completa
     using (VirtualStoreContext context = new VirtualStoreContext())
     {
         var customer = context.Customers.FirstOrDefault(x => x.CustomerId == customer1.CustomerId);
         //var lista = customer.ShoppingCarts;
         //int listac = lista!=null?lista.Count:0;
         Assert.IsNotNull(customer);
     }
 }
Example #23
0
        public void LazyLoadTestOutContext()
        {
            //Si esta fuera de contexto using, hace q genere error al tratar de recueprar indformacion interna
            LlenarDatos();
            Customer customer = null;

            using (VirtualStoreContext context = new VirtualStoreContext())
            {
                customer = context.Customers.FirstOrDefault(x => x.CustomerId == customer1.CustomerId);
            }
            Assert.IsNotNull(customer);
        }
Example #24
0
        public void IncludeTest()
        {
            LlenarDatos();
            Customer customer = null;

            using (VirtualStoreContext context = new VirtualStoreContext())
            {
                customer = context.Customers
                           .Include(x => x.ShoppingCarts)
                           .Include(x => x.ShoppingCarts.Select(y => y.Items))
                           .Include(x => x.ShoppingCarts.Select(y => y.Items.Select(z => z.Product)))
                           .FirstOrDefault(x => x.CustomerId == customer1.CustomerId);
            }
            Assert.IsNotNull(customer);
        }
Example #25
0
        public void GetCustomers_ByCountry()
        {
            using (VirtualStoreContext context = new VirtualStoreContext())
            {
                var customers = context.Customers.Where(c => c.Residence.Country == "Peru").ToList();

                var customers1 = (from c in context.Customers
                                  where c.Residence.Country == "Peru"
                                  select c).ToList();

                Assert.IsNotNull(customers);

                Assert.AreEqual(customers[0].FirstName, customer1.FirstName);
                Assert.AreEqual(customers[0].LastName, customer1.LastName);
            }
        }
Example #26
0
 private IEnumerable <dynamic> GetCustomers_GroupedByCountry_Dynamic()
 {
     using (VirtualStoreContext context = new VirtualStoreContext())
     {
         var result = context.Customers
                      .GroupBy(x => x.Residence.Country)
                      .Select(x => new
         {
             Country   = x.Key,
             Customers = x.Select(y => new
             {
                 Id   = y.CustomerId,
                 Name = y.LastName + ", " + y.FirstName
             })
         });
         return(result.ToList());
     }
 }
Example #27
0
        public void GetCustomers_GroupedByCountry()
        {
            using (VirtualStoreContext context = new VirtualStoreContext())
            {
                var customerGrouped = (from customer in context.Customers
                                       group customer by customer.Residence.Country into g
                                       select new
                {
                    Country = g.Key,
                    Customer = g
                }).ToList();

                Assert.AreEqual(customerGrouped.Count(), 2);

                Assert.AreEqual(customerGrouped[0].Country, "Argentina");
                Assert.AreEqual(customerGrouped[0].Customer.Count(), 2);
                Assert.AreEqual(customerGrouped[1].Country, "Peru");
                Assert.AreEqual(customerGrouped[1].Customer.Count(), 1);
            }
        }
Example #28
0
        public void GetAllCustomers()
        {
            using (VirtualStoreContext context = new VirtualStoreContext())
            {
                var customers = context.Customers.ToList();

                Assert.IsNotNull(customers);
                Assert.AreEqual(customers.Count, 3);


                Assert.AreEqual(customers[0].FirstName, customer1.FirstName);
                Assert.AreEqual(customers[0].LastName, customer1.LastName);

                Assert.AreEqual(customers[1].FirstName, customer2.FirstName);
                Assert.AreEqual(customers[1].LastName, customer2.LastName);

                Assert.AreEqual(customers[2].FirstName, customer3.FirstName);
                Assert.AreEqual(customers[2].LastName, customer3.LastName);
            }
        }
Example #29
0
        /// <summary>
        /// Elimina la entidad incluyendo la informacion extendida
        /// en caso de tenerla
        /// </summary>
        /// <param name="entity"></param>
        public void DeleteIncludeExtended(Employee entity)
        {
            using (VirtualStoreContext context = new VirtualStoreContext())
            {
                if (entity.EmployeeExt == null)
                {
                    entity.EmployeeExt = new EmployeeExtended()
                    {
                        EmployeeId = entity.EmployeeId
                    }
                }
                ;

                context.Employees.Attach(entity);
                context.Employees.Remove(entity);

                context.SaveChanges();
            }
        }
    }
Example #30
0
        public void GetAllCustomers_UsingDynamic()
        {
            //Recuperamos la lista de cliente agrupada por pais
            //
            IEnumerable <dynamic> dynamicCustomers = GetCustomers_GroupedByCountry_Dynamic();

            //Assert
            Assert.AreEqual(dynamicCustomers.Count(), 2);

            dynamic elem1 = dynamicCustomers.ElementAt(0);

            Assert.AreEqual(elem1.Country, "Argentina");
            Assert.AreEqual(elem1.Customers.Count, 2);

            dynamic elem2 = dynamicCustomers.ElementAt(1);

            Assert.AreEqual(elem2.Country, "Peru");
            Assert.AreEqual(elem2.Customers.Count, 1);

            //Validamos contra la lista original
            List <Customer> customers;

            using (VirtualStoreContext context = new VirtualStoreContext())
            {
                customers = context.Customers.ToList();
            }

            foreach (dynamic country in dynamicCustomers)
            {
                foreach (dynamic customer in country.Customers)
                {
                    var exist = customers.Any(x => x.CustomerId == customer.Id &&
                                              x.LastName + ", " + x.FirstName == customer.Name);
                    Assert.IsTrue(exist);
                }
            }
        }