Example #1
0
        public IQueryable <ProfileBox> GetNotScannedProfileBoxesOlderThanStoredYears()
        {
            var query = _profileBoxRepository.Table;

            query = query.Where(x => (x.StatusId == (short)ProfileBoxStatus.Stored || x.StatusId == (short)ProfileBoxStatus.Packed) &&
                                !x.ProfileType.Scanned &&
                                DateTime.Now > DbFunctions.AddYears(x.CreatedDate, x.ProfileType.StoredYears));
            return(query);
        }
Example #2
0
        public static IQueryable <Membre> ListeMembres(bool?premium = null, int?ageMin = null, int?ageMax = null, int?noProvince = null, int?noVille = null, bool membresDesactiver = false)
        {
            ClubContactContext db = new ClubContactContext();

            #region trouverAgeEnChiffre
            //DateTime? dateAgeMax = null;
            //DateTime? dateAgeMin = null;

            //if (ageMax != null)
            //{
            //    dateAgeMax = DateTime.Now.AddYears(-(int)ageMax);
            //}

            //if (ageMin != null)
            //{
            //    dateAgeMin = DateTime.Now.AddYears(-(int)ageMin);
            //}
            #endregion

            IQueryable <Membre> lesMembres = db.Membres;

            if (ageMin != null)
            {
                lesMembres = (from m in lesMembres
                              let years = DateTime.Now.Year - ((DateTime)m.dateNaissance).Year
                                          let birthdayThisYear = DbFunctions.AddYears(m.dateNaissance, years)

                                                                 where ageMax >= (birthdayThisYear > DateTime.Now ? years - 1 : years)
                                                                 select m
                              );
            }
            if (ageMax != null)
            {
                lesMembres = (from m in lesMembres
                              let years = DateTime.Now.Year - ((DateTime)m.dateNaissance).Year
                                          let birthdayThisYear = DbFunctions.AddYears(m.dateNaissance, years)

                                                                 where ageMin <= (birthdayThisYear > DateTime.Now ? years - 1 : years)
                                                                 select m
                              );
            }

            return(lesMembres
                   .Where(m => (premium == null ? true : false || m.premium == premium) &&
                          (noProvince == null ? true : false || m.noProvince == noProvince) &&
                          (noVille == null ? true : false || m.noVille == noVille) &&

                          (membresDesactiver == false ? (m.compteSupprimeParAdmin == null && m.dateSuppressionDuCompte == null) :
                           (m.compteSupprimeParAdmin != null && m.dateSuppressionDuCompte != null))

                          //((dateAgeMax == null ? true : false) || m.dateNaissance >= dateAgeMax) &&
                          //((dateAgeMin == null ? true : false) || m.dateNaissance <= dateAgeMin)
                          ));
        }
        public void DbFunctionsTests_AddYears_DateTime_Test()
        {
            var result = this.GetOrderQuery().Select(x => (DateTime)DbFunctions.AddYears(this.TestDateTime, 1)).First();

            Assert.AreEqual(YEAR + 1, result.Year);
            Assert.AreEqual(MONTH, result.Month);
            Assert.AreEqual(DAY, result.Day);
            Assert.AreEqual(HOUR, result.Hour);
            Assert.AreEqual(MINUTE, result.Minute);
            Assert.AreEqual(SECOND, result.Second);
        }
Example #4
0
        public IQueryable <Profile> GetNeedToDeleteProfiles(int distributorExpiryYears)
        {
            var query = _profileRepository.Table;

            query = query.Where(x => x.StatusId == (short)ProfileStatus.Valid &&
                                (
                                    (DateTime.Now > DbFunctions.AddYears(x.CreatedDate, x.ProfileType.StoredYears)) ||      // Now > CreatedDate + StoredYears
                                    (DateTime.Now > DbFunctions.AddYears(x.Distributor.ExpiryDate, distributorExpiryYears)) // Now > Distributor Expiry Date + n year
                                ));
            return(query);
        }
        public void DateFunctions()
        {
            using (var context = new BloggingContext(ConnectionString))
            {
                IQueryable <int> oneRow = context.Posts.Where(p => false).Select(p => 1).Concat(new int[] { 1 });

                var dateAdds = oneRow.Select(p => new List <DateTime?>
                {
                    DbFunctions.AddDays(new DateTime(2014, 2, 28), 1),
                    DbFunctions.AddHours(new DateTime(2014, 2, 28, 23, 0, 0), 1),
                    DbFunctions.AddMinutes(new DateTime(2014, 2, 28, 23, 59, 0), 1),
                    DbFunctions.AddSeconds(new DateTime(2014, 2, 28, 23, 59, 59), 1),
                    DbFunctions.AddMilliseconds(new DateTime(2014, 2, 28, 23, 59, 59, 999), 2 - p),
                    DbFunctions.AddMicroseconds(DbFunctions.AddMicroseconds(new DateTime(2014, 2, 28, 23, 59, 59, 999), 500), 500),
                    DbFunctions.AddNanoseconds(new DateTime(2014, 2, 28, 23, 59, 59, 999), 999999 + p),
                    DbFunctions.AddMonths(new DateTime(2014, 2, 1), 1),
                    DbFunctions.AddYears(new DateTime(2013, 3, 1), 1)
                }).First();
                foreach (var result in dateAdds)
                {
                    Assert.IsTrue(result.Value == new DateTime(2014, 3, 1, 0, 0, 0));
                }

                var dateDiffs = oneRow.Select(p => new {
                    a = DbFunctions.DiffDays(new DateTime(1999, 12, 31, 23, 59, 59, 999), new DateTime(2000, 1, 1, 0, 0, 0)),
                    b = DbFunctions.DiffHours(new DateTime(1999, 12, 31, 23, 59, 59, 999), new DateTime(2000, 1, 1, 0, 0, 0)),
                    c = DbFunctions.DiffMinutes(new DateTime(1999, 12, 31, 23, 59, 59, 999), new DateTime(2000, 1, 1, 0, 0, 0)),
                    d = DbFunctions.DiffSeconds(new DateTime(1999, 12, 31, 23, 59, 59, 999), new DateTime(2000, 1, 1, 0, 0, 0)),
                    e = DbFunctions.DiffMilliseconds(new DateTime(1999, 12, 31, 23, 59, 59, 999), new DateTime(2000, 1, 1, 0, 0, 0)),
                    f = DbFunctions.DiffMicroseconds(new DateTime(1999, 12, 31, 23, 59, 59, 999), new DateTime(2000, 1, 1, 0, 0, 0)),
                    g = DbFunctions.DiffNanoseconds(new DateTime(1999, 12, 31, 23, 59, 59, 999), new DateTime(2000, 1, 1, 0, 0, 0)),
                    h = DbFunctions.DiffMonths(new DateTime(1999, 12, 31, 23, 59, 59, 999), new DateTime(3000, 1, 1, 0, 0, 0)),
                    i = DbFunctions.DiffYears(new DateTime(1999, 12, 31, 23, 59, 59, 999), new DateTime(3000, 1, 1, 0, 0, 0)),
                    j = DbFunctions.DiffYears(null, new DateTime(2000, 1, 1)),
                    k = DbFunctions.DiffMinutes(new TimeSpan(1, 2, 3), new TimeSpan(4, 5, 6)),
                    l = DbFunctions.DiffMinutes(new TimeSpan(1, 2, 3), null)
                }).First();
                Assert.AreEqual(dateDiffs.a, 1);
                Assert.AreEqual(dateDiffs.b, 1);
                Assert.AreEqual(dateDiffs.c, 1);
                Assert.AreEqual(dateDiffs.d, 1);
                Assert.AreEqual(dateDiffs.e, 1);
                Assert.AreEqual(dateDiffs.f, 1000);
                Assert.AreEqual(dateDiffs.g, 1000000);
                Assert.AreEqual(dateDiffs.h, 12001);
                Assert.AreEqual(dateDiffs.i, 1001);
                Assert.AreEqual(dateDiffs.j, null);
                Assert.AreEqual(dateDiffs.k, 183);
                Assert.AreEqual(dateDiffs.l, null);
            }
        }
        public void DateTimeAddYears()
        {
            DateTime date = stored.AddYears(-1);

#if !EFOLD
            var q = this.Entities
                    .Where(x =>
                           DbFunctions.AddYears(x.DateTime, -1) == date);
#else
            var q = this.Entities
                    .Where(x =>
                           EntityFunctions.AddYears(x.DateTime, -1) == date);
#endif

            q.Should().NotBeEmpty();
        }
Example #7
0
        public void DateTimeOffsetAddYears()
        {
            DateTimeOffset offset = stored.AddYears(-1);

#if !EFOLD
            var q = this.Entities
                    .Where(x =>
                           DbFunctions.AddYears(x.Offset, -1) == offset);
#else
            var q = this.Entities
                    .Where(x =>
                           EntityFunctions.AddYears(x.Offset, -1) == offset);
#endif

            q.Should().NotBeEmpty();
        }
Example #8
0
        public List <tb_person> FindPatientsByManyConds(String name, String address, String gender, String age, String time)
        {
            using (database = new ModelEntities())
            {
                var query = database.tb_person.AsQueryable();
                if (name != null && !name.Equals(""))
                {
                    query = query.Where(p => p.FullName.Contains(name));
                }
                if (address != null && !address.Equals(""))
                {
                    query = query.Where(p => p.Address.Contains(address));
                }
                if (gender != null && !gender.Equals(""))
                {
                    query = query.Where(p => p.Gender.Equals(gender));
                }
                switch (age.ToString())
                {
                case "<5":
                    query = query.Where(p => p.Birthday >= DbFunctions.AddYears(DateTime.Now, -5));
                    break;

                case "5-10":
                    query = query.Where(p => p.Birthday >= DbFunctions.AddYears(DateTime.Now, -10) && p.Birthday <= DbFunctions.AddYears(DateTime.Now, -5));
                    break;

                case "10-15":
                    query = query.Where(p => p.Birthday >= DbFunctions.AddYears(DateTime.Now, -15) && p.Birthday <= DbFunctions.AddYears(DateTime.Now, -10));
                    break;

                case "15-30":
                    query = query.Where(p => p.Birthday >= DbFunctions.AddYears(DateTime.Now, -30) && p.Birthday <= DbFunctions.AddYears(DateTime.Now, -15));
                    break;

                case "30-60":
                    query = query.Where(p => p.Birthday >= DbFunctions.AddYears(DateTime.Now, -60) && p.Birthday <= DbFunctions.AddYears(DateTime.Now, -30));
                    break;

                case ">60":
                    query = query.Where(p => p.Birthday <= DbFunctions.AddYears(DateTime.Now, -60));
                    break;
                }

                return(query.ToList());
            }
        }
Example #9
0
        private void yearInactivity()
        {
            var activeSub = (from a in music.Abonné
                             join em in music.Emprunter on a.Code_Abonné equals em.Code_Abonné
                             where DbFunctions.AddYears(em.Date_Emprunt.Value, 1).Value.CompareTo(DateTime.Now) >= 0
                             select a).ToList().Distinct();
            var sub = (from a in music.Abonné
                       join em in music.Emprunter on a.Code_Abonné equals em.Code_Abonné
                       select a).ToList().Distinct();

            foreach (Abonné a in sub)
            {
                if (!activeSub.Contains(a))
                {
                    listBox4.Items.Add(a);
                }
            }
        }
Example #10
0
        public void Load(IQueryable <Statistic> query)
        {
            query = query.Where(it => it.RequestDate > DbFunctions.AddYears(DateTime.Now, -1));

            var days  = query.GroupBy(it => DbFunctions.TruncateTime(it.RequestDate));
            var month = query.GroupBy(it => it.RequestDate.Month);
            var weeks = query.GroupBy(it => DbFunctions.DiffDays(DbFunctions.CreateDateTime(DateTime.Now.Year, 1, 1, 1, 1, 1), it.RequestDate) / 7);
            var week  = CultureInfo.CurrentCulture.Calendar.GetWeekOfYear(DateTime.Now, CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday) - 10;

            _lastDays = days
                        .Where(it => it.Key.Value > DbFunctions.AddMonths(DateTime.Now, -1))
                        .ToDictionary(q => q.Key.Value, q => q.DistinctBy(it => it.RequestIP).Count());
            _lastWeeks = weeks
                         .Where(it => it.Key > week)
                         .ToDictionary(q => q.Key.Value,
                                       q => q.DistinctBy(it => it.RequestIP).Count());
            _lastMonths = month
                          .ToDictionary(q => q.Key > DateTime.Now.Month - 1 ? DateTime.Now.Year + "-" + (q.Key > 9 ? q.Key.ToString() : "0" + q.Key) : DateTime.Now.Year - 1 + "-" + (q.Key > 9 ? q.Key.ToString() : "0" + q.Key),
                                        q => q.DistinctBy(it => it.RequestIP).Count());
        }
 public DateTime?AddYears(DateTime?date, int?yearsToAdd)
 {
     return(DbFunctions.AddYears(date, yearsToAdd));
 }
        static void Main(string[] args)
        {
            try
            {
                //1.- Instanciamos el contexto de Entity Framework
                BBDDLocalEntidades db = new BBDDLocalEntidades();

                //Se le asigna un valor en segundos, si se le asigna 0 entonces obligamos a EF a esperar indefinidamente la respuesta de SQL
                db.Database.CommandTimeout = 0;

                //Lazy Loading
                db.Configuration.LazyLoadingEnabled   = false;
                db.Configuration.ProxyCreationEnabled = false;

                #region Beneficios en general de LINQ

                #region Combinación de cadenas con y sin LINQ

                // Si quisieramos combinar todas estas cadenas en una sala sin LINQ hariamos lo siguiente

                string[] paises = { "India", "US", "UK", "Canada", "Australia" };

                #region Sin LINQ Unión de cadenas

                //string resultadoSinLINQ = string.Empty;
                //for (int i = 0; i < paises.Length; i++)
                //{
                //    resultadoSinLINQ = resultadoSinLINQ + paises[i] + ", ";
                //}

                //int lastIndexSinLINQ = resultadoSinLINQ.LastIndexOf(",");
                //resultadoSinLINQ = resultadoSinLINQ.Remove(lastIndexSinLINQ);

                //Console.WriteLine(resultadoSinLINQ);

                #endregion

                #region Con LINQ

                // Si quisieramos combinar todas estas cadenas en una sala sin LINQ hariamos lo siguiente

                //string result = paises.Aggregate((a, b) => a + ", " + b);

                #endregion

                #endregion

                #region Multiplicación de todos los números con y sin LINQ

                // Si quisieramos multiplicar todos estos números

                int[] Numbers = { 2, 3, 4, 5 };

                #region Sin LINQ

                int result = 1;
                foreach (int i in Numbers)
                {
                    result = result * i;
                }

                Console.WriteLine(result);

                #endregion

                #region Con LINQ

                int resultado = Numbers.Aggregate((a, b) => a * b);

                Console.WriteLine(resultado);

                #endregion

                #endregion


                #endregion

                #region Consulta con Where

                //#region Query Syntax

                //var querySyntaxConsultaSimple = (from Empleado in db.Empleado
                //            where Empleado.Salario > 2000M
                //            select Empleado).ToList();

                //foreach (var item in querySyntaxConsultaSimple)
                //{
                //    Console.WriteLine(item.Nombre + " - " + item.Salario);
                //}


                //#endregion

                //#region Method Syntax

                //var queryMethodSyntaxConsultaSimple = db.Empleado
                //                .Where(x => x.Salario > 2000M)
                //                .Select(x => new
                //                {
                //                    x.Nombre,
                //                    x.Salario
                //                }).ToList();

                //foreach (var item in queryMethodSyntaxConsultaSimple)
                //{
                //    Console.WriteLine(item.Nombre + " - " + item.Salario);
                //}

                //#endregion

                #endregion

                #region Consulta Join con Where



                #region Query Syntax

                //string departamento = Console.ReadLine();

                //var querySyntax = (from Empleado in db.Empleado
                //             join Departamento in db.Departamento
                //             on Empleado.CodigoDepartamento equals Departamento.CodigoDepartamento
                //             where Empleado.Salario > 2000M && Departamento.Departamento1.Contains(departamento)
                //             select new
                //             {
                //                 Empleado.Nombre,
                //                 Empleado.Salario,
                //                 Departamento = Departamento.Departamento1
                //             }).ToList();


                //foreach (var item in querySyntax)
                //{
                //    Console.WriteLine(item.Nombre + " - " + item.Salario + "-" + item.Departamento);
                //}

                #endregion

                #region Method Syntax

                //string departamento = Console.ReadLine();

                //var methodSyntax = db.Empleado.Join(db.Departamento
                //    , EmpleadoTP => EmpleadoTP.CodigoDepartamento
                //    , DepartamentoTF => DepartamentoTF.CodigoDepartamento,
                //    (EmpleadoTP, DepartamentoTF) => new
                //    {
                //        EmpleadoTP.Nombre,
                //        EmpleadoTP.Salario,
                //        Departamento = DepartamentoTF.Departamento1

                //    }).Where(x => x.Salario > 2000M && x.Departamento.Contains(departamento)).ToList();


                //foreach (var item in methodSyntax)
                //{
                //    Console.WriteLine(item.Nombre + " - " + item.Salario + "-" + item.Departamento);
                //}

                #endregion



                #endregion

                #region Consultas Max y Min

                #region Query Syntax

                //var queryCountSalarioMayor2M = (from Empleado in db.Empleado
                //                                where Empleado.Salario > 2000M
                //                                select Empleado).Count();

                //var queryTotalEmpleados = (from Empleado in db.Empleado select Empleado).Count();

                //var queryCountSalarioMenor5M = (from Empleado in db.Empleado where Empleado.Salario < 5000 select Empleado).Count();

                //decimal? querySalarioMaximo = (from Empleado in db.Empleado select Empleado.Salario).Max();

                //var queryPersonaSalarioMaximo = (from Empleado in db.Empleado
                //                                 orderby Empleado.Salario descending
                //                                 select Empleado).FirstOrDefault();

                //var queryPersonaSalarioMinimo = (from Empleado in db.Empleado
                //                                where Empleado.Salario == db.Empleado.Min(w => w.Salario)
                //                                select Empleado).FirstOrDefault();

                #endregion

                #region Method Syntax

                //var queryCountSalarioMayor2M = db.Empleado.Where(x => x.Salario > 2000M).Count();

                //var queryTotalEmpleados = db.Empleado.Count();

                //var queryCountSalarioMenor5M = db.Empleado.Where(w => w.Salario < 5000).Count();

                //decimal? querySalarioMaximo = db.Empleado.Max(w => w.Salario);

                //var queryPersonaSalarioMaximo = db.Empleado.OrderByDescending(x => x.Salario).FirstOrDefault();

                //var queryPersonaSalarioMinimo = db.Empleado.OrderBy(x => x.Salario).FirstOrDefault();



                #endregion

                //Console.WriteLine("Personas con salario mayor a Q2000 = " + queryCountSalarioMayor2M);
                //Console.WriteLine("Número de Empleados = " + queryTotalEmpleados);
                //Console.WriteLine("Personas con salario menor  a Q5000 = " + queryCountSalarioMenor5M);
                //Console.WriteLine("Salario maximo = " + querySalarioMaximo);
                //Console.WriteLine("Persona con Salario Máximo: " + queryPersonaSalarioMaximo.Nombre);
                //Console.WriteLine("Persona con Salario Mínimo: " + queryPersonaSalarioMinimo.Nombre);


                #endregion

                #region Consulta Promedio Salarial por Departamento

                #region Query Syntax

                //var queryPromedioSalarioPorDepartamento = (from Empleado in db.Empleado
                //                                           join Departamento in db.Departamento
                //                                           on Empleado.CodigoDepartamento equals Departamento.CodigoDepartamento

                //                                           group Empleado by Departamento into agrupacion
                //                                           select new
                //                                           {
                //                                               CodigoDepartamento = agrupacion.Key.CodigoDepartamento,
                //                                               agrupacion.Key.Departamento1,
                //                                               Promedio = agrupacion.Average(w => w.Salario)
                //                                           }).ToList();

                #endregion

                #region Method Syntax

                //var queryPromedioSalarioPorDepartamento = db.Empleado.Join(db.Departamento
                //    , EmpleadoTP => EmpleadoTP.CodigoDepartamento
                //    , DepartamentoTF => DepartamentoTF.CodigoDepartamento,
                //    (EmpleadoTP, DepartamentoTF) => new
                //    {
                //        Empleado = EmpleadoTP,
                //        Departamento = DepartamentoTF

                //    }).ToList()
                //    .GroupBy(x => x.Departamento)
                //    .Select(x => new
                //    {
                //        x.Key.CodigoDepartamento,
                //        x.Key.Departamento1,
                //        Promedio = x.Average(y => y.Empleado.Salario)

                //    }).ToList();



                #endregion


                //foreach (var item in queryPromedioSalarioPorDepartamento)
                //{
                //    Console.WriteLine(item.Departamento1 + " = " + item.Promedio);
                //}

                #endregion

                #region Consulta Total Empleado Por Departamento


                #region Query Syntax

                //string departamento = Console.ReadLine();

                //var queryEmpleadoPorDepartamento = (from Empleado in db.Empleado
                //                                    join Departamento in db.Departamento
                //                                    on Empleado.CodigoDepartamento equals Departamento.CodigoDepartamento

                //                                    group Empleado by Departamento into agrupacion
                //                                    where agrupacion.Key.Departamento1.Contains(departamento)
                //                                    select new
                //                                    {
                //                                        CodigoDepartamento = agrupacion.Key.CodigoDepartamento,
                //                                        agrupacion.Key.Departamento1,
                //                                        NoEmpleados = agrupacion.Count()
                //                                    }).ToList();

                #endregion

                #region Method Syntax

                //string departamento = Console.ReadLine();

                //var queryEmpleadoPorDepartamento = db.Empleado.Join(db.Departamento
                //    , EmpleadoTP => EmpleadoTP.CodigoDepartamento
                //    , DepartamentoTF => DepartamentoTF.CodigoDepartamento,
                //    (EmpleadoTP, DepartamentoTF) => new
                //    {
                //        Empleado = EmpleadoTP,
                //        Departamento = DepartamentoTF

                //    })
                //    .Where(x => x.Departamento.Departamento1.Contains(departamento) )
                //    .GroupBy(x => x.Departamento)
                //    .Select(x => new
                //    {
                //        x.Key.CodigoDepartamento,
                //        x.Key.Departamento1,
                //        NoEmpleados = x.Count()

                //    }).ToList();

                #endregion

                //foreach (var item in queryEmpleadoPorDepartamento)
                //{
                //    Console.WriteLine(item.Departamento1 + " = " + item.NoEmpleados);
                //}

                #endregion

                #region Consulta Order By

                #region Query Syntax

                //var queryEmpleadoPorDepartamento = (from Empleado in db.Empleado
                //                                    orderby Empleado.Salario //descending
                //                                    select Empleado
                //                                   ).ToList();

                #endregion

                #region Method Syntax

                //var queryEmpleadoPorDepartamento = db.Empleado.OrderBy(x => x.Salario).Select(x => x);

                #endregion

                //foreach (var item in queryEmpleadoPorDepartamento)
                //{
                //    Console.WriteLine(item.Nombre + " = " + item.Salario);
                //}


                #endregion

                #region Consulta Take - Skip

                #region Query Syntax

                //string departamento = Console.ReadLine();

                //var queryEmpleadoPorDepartamento = (from Empleado in db.Empleado
                //                                    join Departamento in db.Departamento
                //                                    on Empleado.CodigoDepartamento equals Departamento.CodigoDepartamento
                //                                    where Departamento.Departamento1.Contains(departamento)
                //                                    orderby Empleado.Salario descending
                //                                    select Empleado
                //                                   ).Take(4).ToList();

                #endregion

                #region Method Syntax

                //string departamento = Console.ReadLine();

                //var queryEmpleadoPorDepartamento = db.Empleado.Join(db.Departamento
                //    , EmpleadoTP => EmpleadoTP.CodigoDepartamento
                //    , DepartamentoTF => DepartamentoTF.CodigoDepartamento,
                //    (EmpleadoTP, DepartamentoTF) => new
                //    {
                //        Empleado = EmpleadoTP,
                //        Departamento = DepartamentoTF

                //    })
                //    .Where(x => x.Departamento.Departamento1.Contains(departamento))

                //    .Select(x => x.Empleado)
                //    .Take(4)
                //    .ToList();


                #endregion


                //foreach (var item in queryEmpleadoPorDepartamento)
                //{
                //    Console.WriteLine(item.Nombre + " = " + item.Salario);
                //}

                //var query = (from Empleado in db.Empleado
                //             join Departamento in db.Departamento
                //                                   on Empleado.CodigoDepartamento equals Departamento.CodigoDepartamento
                //             where Departamento.Departamento1.Contains(departamento)
                //             orderby Empleado.Salario descending
                //            select Empleado
                //                                   ).Skip(2).First();

                //Console.WriteLine(query.Nombre + " = " + query.Salario);



                #endregion

                #region Consulta con FirstOrDefault

                #region Query Syntax

                //var queryPersonaSalarioMax = (from Empleado in db.Empleado
                //                                where Empleado.Salario == db.Empleado.Max(w => w.Salario)
                //                                select Empleado).FirstOrDefault();

                #endregion

                #region Method Syntax

                //var queryPersonaSalarioMax = db.Empleado.Where(x => x.Salario == db.Empleado.Max(w => w.Salario)).FirstOrDefault();

                #endregion



                //if (queryPersonaSalarioMax != null)
                //    Console.WriteLine(queryPersonaSalarioMax.Nombre + " - " + queryPersonaSalarioMax.Salario);

                #endregion


                #region Consulta con Element At

                #region Query Syntax
                //string departamento = Console.ReadLine();

                //var query = (from Empleado in db.Empleado
                //            join Departamento in db.Departamento
                //            on Empleado.CodigoDepartamento equals Departamento.CodigoDepartamento
                //            where Departamento.Departamento1.Contains(departamento)

                //            select new
                //            {
                //                Departamento.CodigoDepartamento,
                //                Departamento.Departamento1,
                //                Empleado.Nombre,
                //                Empleado.Salario
                //            }).ToList().ElementAtOrDefault(2);

                #endregion

                #region Method Syntax

                //string departamento = Console.ReadLine();

                //var query = db.Empleado.Join(db.Departamento
                //    , EmpleadoTP => EmpleadoTP.CodigoDepartamento
                //    , DepartamentoTF => DepartamentoTF.CodigoDepartamento,
                //    (EmpleadoTP, DepartamentoTF) => new
                //    {
                //        Empleado = EmpleadoTP,
                //        Departamento = DepartamentoTF

                //    })
                //    .Where(x => x.Departamento.Departamento1.Contains(departamento))

                //    .Select(x => new
                //    {
                //        x.Departamento.CodigoDepartamento,
                //        x.Departamento.Departamento1,
                //        x.Empleado.Nombre,
                //        x.Empleado.Salario
                //    })
                //    .ToList().ElementAtOrDefault(2);


                #endregion

                //if (query!=null)
                //{


                //    Console.WriteLine(query.Departamento1 + " - " + query.Nombre + " - " + query.Salario );
                //}


                #endregion

                #region Uso de All and ANY

                #region Query and Methos Syntax

                // var query = (from Empleado in db.Empleado
                //              select Empleado).ToList().All(w => w.Salario > 3000);

                //Console.WriteLine(query?"Todos los empleados ganan mas de Q3000":"No todos los empleados ganan mas de Q3000");


                // var queryAny = (from Empleado in db.Empleado
                //              select Empleado).ToList().Any(w => w.Salario > 3000);

                // Console.WriteLine(query ? "Algunos empleados ganan mas de Q3000" : "Ninguno de los empleados ganan mas de Q3000");


                #endregion


                #endregion

                #region Consulta por lista de código de Empleado


                //List<int> listadoDeEmpleados = new List<int>{ 1, 4, 6, 8, 9 };
                //var queryEmpleadoPorDepartamento = (from Empleado in db.Empleado
                //                                    where listadoDeEmpleados.Contains(Empleado.CodigoEmpleado)
                //                                    select Empleado
                //                                   );

                //foreach (var item in queryEmpleadoPorDepartamento)
                //{
                //    Console.WriteLine(item.Nombre + " = " + item.Salario);
                //}
                #endregion
                #region Consulta para obtener IGSS

                // Uso del comando LET

                //var queryEmpleadoPorDepartamento = (from Empleado in db.Empleado
                //                                    let IGSS = Empleado.Salario * 0.0483M
                //                                    select new
                //                                    {
                //                                        Empleado.Nombre,
                //                                        Empleado.Salario,
                //                                        IGSS,
                //                                        SalarioFinal = Empleado.Salario-IGSS
                //                                    }
                //                                   );

                //foreach (var item in queryEmpleadoPorDepartamento)
                //{
                //    Console.WriteLine(item.Nombre + " -" + item.Salario +" - "+item.IGSS+" - "+ item.SalarioFinal);
                //}
                #endregion

                #region Consulta para Empleados sin departamento

                // Para hacer LEFT JOIN es más fácil con Query Syntax

                //var queryEmpleadoPorDepartamento = (from Empleado in db.Empleado
                //                                    join D in db.Departamento
                //                                    on Empleado.CodigoDepartamento equals D.CodigoDepartamento into leftDepartamento
                //                                    from Departamento in leftDepartamento.DefaultIfEmpty()
                //                                    where Empleado.CodigoDepartamento == null
                //                                    select new
                //                                    {
                //                                        Empleado.Nombre,
                //                                        Empleado.Salario,
                //                                        Departamento = Departamento == null ? "Sin asignar" : Departamento.Departamento1
                //                                    }
                //                                   );

                //foreach (var item in queryEmpleadoPorDepartamento)
                //{
                //    Console.WriteLine(item.Nombre + " -" + item.Salario + " - " + item.Departamento);
                //}
                #endregion

                #region Trabajando con Fechas



                // En LINQ to Entity, no podemos utilizar los métodos disponibles para el trabajo con fechas, por ejemplo lo siguiente da error, en LINQ to Objects no tendriamos ese problema

                //var query = db.Empleado.
                //    Select(x => new
                //    {

                //        Empleado = x.Nombre,
                //        Fecha = x.Fecha,
                //        FechaRestando5Dias = x.Fecha.Value.AddDays(-5).Date,
                //        AñoAgregado = x.Fecha.Value.AddYears(10)
                //    }).ToList();



                /* Para ello, disponemos de la clase DbFunctions, que nos permite realizar lo anterior sin errores
                 * Ejemplo https://hernandgr.wordpress.com/2015/07/21/tip-clase-dbfunctions-usando-funciones-canonicas-linq-to-entities-en-c-sharp/
                 */

                var queryConDbFunctions = db.Empleado.
                                          Select(x => new
                {
                    Empleado           = x.Nombre,
                    Fecha              = x.Fecha,
                    FechaRestando5Dias = DbFunctions.AddDays(x.Fecha.Value, -5),
                    AñoAgregado        = DbFunctions.AddYears(x.Fecha, 10).Value
                }).ToList();

                #endregion

                #region Ejemplo uso de LIKE

                /* Se pueden serguir los siguientes enlaces como apoyo
                 * https://www.cjorellana.net/2012/06/like-en-entity-framework.html
                 */

                var ejemploCadenaLike = "ar";


                /* Todos los empleados que contienen la cadena ar
                 * SELECT * FROM Empleado WHERE Nombre like '%ar%'
                 */

                var matchesEjemplo1 = (from m in db.Empleado
                                       where m.Nombre.Contains(ejemploCadenaLike)
                                       select m).ToList();

                /* Todos los empleados que empiezan con la cadena ar
                 * SELECT * FROM Empleado WHERE Nombre like '%ar'
                 */

                var matchesEjemplo2 = (from m in db.Empleado
                                       where m.Nombre.ToLower().StartsWith(ejemploCadenaLike)
                                       select m).ToList();

                /* Todos los empleados que finalizan con la cadena
                 * SELECT * FROM Empleado WHERE Nombre like 'ar%'
                 */

                var matchesEjemplo3 = (from m in db.Empleado
                                       where m.Nombre.ToLower().EndsWith(ejemploCadenaLike)
                                       select m).ToList();

                /* Todos los empleados que empiezan con la letra t y finalizan con la letra s
                 * SELECT * FROM Empleado WHERE Nombre like 't%s'
                 */

                var matchesEjemplo4 = (from m in db.Empleado
                                       where m.Nombre.ToLower().StartsWith("t") && m.Nombre.ToLower().EndsWith("s")
                                       select m).ToList();


                #endregion

                #region Consulta Compleja



                //var consulta = db.Empleado
                //                    .GroupBy(x => new
                //                    {
                //                        x.CodigoDepartamento,
                //                        x.Departamento.Departamento1
                //                    }).Select(x => new
                //                    {
                //                        x.Key.CodigoDepartamento,
                //                        x.Key.Departamento1,


                //                        EmpleadosSalariosMasBajos = db.Empleado
                //                            .Where(y => y.CodigoDepartamento == x.Key.CodigoDepartamento)
                //                            .Select(y => new
                //                            {
                //                                y.CodigoEmpleado,
                //                                y.Nombre,
                //                                y.EmpleadoDireccion.FirstOrDefault().Direccion,
                //                                y.Salario
                //                            }).OrderByDescending(y => y.Salario).Take(5).ToList(),



                //                    }).
                //                    Select(x => new
                //                    {
                //                        CodigoDepartamento = x.CodigoDepartamento == null ? 0 : x.CodigoDepartamento,
                //                        Departamento = x.Departamento1 == null ? "No tiene asignación de departamento" : x.Departamento1,
                //                        x.EmpleadosSalariosMasBajos,
                //                        CodigoEmpleadoSalarioMasAlto = x.EmpleadosSalariosMasBajos.FirstOrDefault().CodigoEmpleado,
                //                        EmpleadoSalarioMasAlto = x.EmpleadosSalariosMasBajos.FirstOrDefault().Nombre,


                //                    }).ToList();

                //foreach (var item in consulta)
                //{
                //    Console.WriteLine(item.Departamento + ": Salario Mas Alto: " + item.CodigoEmpleadoSalarioMasAlto + " - " + item.EmpleadoSalarioMasAlto);
                //    Console.WriteLine("Listado de salarios mas bajos: ");
                //    foreach (var itemSalariosMasBajos in item.EmpleadosSalariosMasBajos)
                //    {
                //        Console.WriteLine(itemSalariosMasBajos.Nombre + "-" + itemSalariosMasBajos.Salario);
                //    }
                //}

                #endregion
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.GetBaseException().Message);
            }
            finally
            {
                Console.ReadLine();
            }
        }
Example #13
0
        public IQueryable <Membre> RechercheMembreAvecProprietes(RechercheViewModel laRecherche, int noMembre)
        {
            #region trouverAgeEnChiffre
            //DateTime? ageMax = null;
            //DateTime? ageMin = null;

            //if (laRecherche.ageMax != null)
            //{
            //    ageMax = DateTime.Now.AddYears(-(int)laRecherche.ageMax);
            //}

            //if (laRecherche.ageMin != null)
            //{
            //    ageMin = DateTime.Now.AddYears(-(int)laRecherche.ageMin);
            //}
            #endregion

            IQueryable <Membre> membresTrouves = db.Membres;
            Membre membreActuel;
            try
            {
                membreActuel = db.Membres.Where(m => m.noMembre == noMembre).Include(m => m.listeNoire).FirstOrDefault();
            }
            catch (Exception e)
            {
                Dictionary <string, string> parametres = new Dictionary <string, string>()
                {
                    { "noMembre", noMembre.ToString() }
                };
                throw Utilitaires.templateException("(Non-Action) RechercheMembreAvecProprietes", "Membres", "Requête LINQ n'a pas fonctionnée ou la BD est inaccessible.", e, parametres);
            }

            //on doit avoir un membre, sinon on ne peut pas tester la distance en KM
            if (membreActuel != null)
            {
                //Si on veut la recherche par KM
                if (laRecherche.distanceKmDeMoi != null)
                {
                    //La BD doit avoir été bien initialisée
                    if (membreActuel.ville.lat != null || membreActuel.ville.lng != null)
                    {
                        double latMembre = (double)membreActuel.ville.lat;
                        double lngMembre = (double)membreActuel.ville.lng;

                        //on définit la requête LINQ to SQL pour trouver les membres à une distance X
                        membresTrouves =
                            #region RequeteSQLCalculsDistance
                            (from m in db.Membres
                             let membreLatitude = (double)m.ville.lat
                                                  let membreLongitude = (double)m.ville.lng
                                                                        let theta = ((lngMembre - membreLongitude) * Math.PI / 180.0)
                                                                                    let requestLat = (latMembre * Math.PI / 180.0)
                                                                                                     let membreLat = (membreLatitude * Math.PI / 180.0)
                                                                                                                     let dist = (SqlFunctions.Sin(requestLat) * SqlFunctions.Sin(membreLat)) +
                                                                                                                                (SqlFunctions.Cos(requestLat) * SqlFunctions.Cos(membreLat) * SqlFunctions.Cos(theta))
                                                                                                                                let cosDist = SqlFunctions.Acos(dist)
                                                                                                                                              let degDist = (cosDist / Math.PI * 180.0)
                                                                                                                                                            let absoluteDist = degDist * 60 * 1.1515
                                                                                                                                                                               let distInKM = absoluteDist * 1.609344
                                                                                                                                                                                              where distInKM < laRecherche.distanceKmDeMoi
                                                                                                                                                                                              select m);
                        #endregion
                    }
                }

                //On ajoute la partie si le membre est connecté (on l'enlève des recherches pour pas qu'il se voit)
                membresTrouves = membresTrouves
                                 .Where(m => (m.noMembre != noMembre) &&
                                        //BlackListe
                                        (!m.listeMembresQuiMontBloque.Select(x => x.noMembre).Contains(membreActuel.noMembre)) &&
                                        (!m.listeNoire.Select(x => x.noMembre).Contains(membreActuel.noMembre))
                                        );
            }


            //Après avoir ajouté les wheres et calculs possibles, on ajoute la query commune et on retourne le tout!
            //la recherche par age sera aussi implémenter de cette façon dans AdminController pour la liste des membres
            if (laRecherche.ageMin != null)
            {
                membresTrouves = (from m in membresTrouves
                                  let years = DateTime.Now.Year - ((DateTime)m.dateNaissance).Year
                                              let birthdayThisYear = DbFunctions.AddYears(m.dateNaissance, years)

                                                                     where laRecherche.ageMax >= (birthdayThisYear > DateTime.Now ? years - 1 : years)
                                                                     select m
                                  );
            }
            if (laRecherche.ageMax != null)
            {
                membresTrouves = (from m in membresTrouves
                                  let years = DateTime.Now.Year - ((DateTime)m.dateNaissance).Year
                                              let birthdayThisYear = DbFunctions.AddYears(m.dateNaissance, years)

                                                                     where laRecherche.ageMin <= (birthdayThisYear > DateTime.Now ? years - 1 : years)
                                                                     select m
                                  );
            }

            membresTrouves = membresTrouves
                             #region RequeteLINQPourTousLesCriteres
                             .Where(m => //On s'assure que le membre n'est pas supprimé, car on n'en veut pas dans notre recherche.
                                    (m.compteSupprimeParAdmin == null && m.dateSuppressionDuCompte == null) &&

                                    //((ageMax == null ? true : false) || DbFunctions.TruncateTime(m.dateNaissance) >= DbFunctions.TruncateTime(ageMax)) && //Signe = ajouté 2017-11-19 Anthony Brochu
                                    //((ageMin == null ? true : false) || DbFunctions.TruncateTime(m.dateNaissance) <= DbFunctions.TruncateTime(ageMin)) && //Signe = ajouté 2017-11-19 Anthony Brochu
                                    ((laRecherche.homme == null ? true : false) || m.homme == laRecherche.homme) &&
                                    ((laRecherche.noRaisonsSite == null ? true : false) || m.listeRaisonsSurSite.Select(r => r.noRaisonSurSite).Contains((laRecherche.noRaisonsSite ?? 0))) &&
                                    ((laRecherche.chercheHomme == null ? true : false) || m.rechercheHomme == laRecherche.chercheHomme) &&
                                    ((laRecherche.noProvince == null ? true : false) || m.noProvince == laRecherche.noProvince) &&
                                    ((laRecherche.noVille == null ? true : false) || m.noVille == laRecherche.noVille) &&
                                    //Caractéristiques Physiques
                                    ((laRecherche.noYeuxCouleur == null ? true : false) || m.noYeuxCouleur == laRecherche.noYeuxCouleur) &&
                                    ((laRecherche.noCheveuxCouleur == null ? true : false) || m.noCheveuxCouleur == laRecherche.noCheveuxCouleur) &&
                                    ((laRecherche.noSilhouette == null ? true : false) || m.noSilhouette == laRecherche.noSilhouette) &&
                                    ((laRecherche.noTaille == null ? true : false) || m.noTaille == laRecherche.noTaille) &&
                                    //Informations supplémentaires
                                    ((laRecherche.fumeur == null ? true : false) || m.fumeur == laRecherche.fumeur) &&
                                    ((laRecherche.noReligion == null ? true : false) || m.noReligion == laRecherche.noReligion) &&
                                    ((laRecherche.noOrigine == null ? true : false) || m.noOrigine == laRecherche.noOrigine) &&
                                    ((laRecherche.noDesirEnfant == null ? true : false) || m.noDesirEnfant == laRecherche.noDesirEnfant) &&
                                    ((laRecherche.noOccupation == null ? true : false) || m.noOccupation == laRecherche.noOccupation) &&
                                    ((laRecherche.noSituationFinanciere == null ? true : false) || m.noSituationFinanciere == laRecherche.noSituationFinanciere) &&
                                    ((laRecherche.noNiveauEtude == null ? true : false) || m.noNiveauEtude == laRecherche.noNiveauEtude) &&

                                    ((laRecherche.nbEnfantsMax == null ? true : false) || m.nbEnfants <= laRecherche.nbEnfantsMax) && //Signe "=" ajouté 2017-11-19 Anthony Brochu
                                    ((laRecherche.nbEnfantsMin == null ? true : false) || m.nbEnfants >= laRecherche.nbEnfantsMin) && //Signe "=" ajouté 2017-11-19 Anthony Brochu

                                    ((laRecherche.nbAnimauxMax == null ? true : false) || m.nbAnimaux <= laRecherche.nbAnimauxMax) && //Signe "=" ajouté 2017-11-19 Anthony Brochu
                                    ((laRecherche.nbAnimauxMin == null ? true : false) || m.nbAnimaux >= laRecherche.nbAnimauxMin)    //Signe "=" ajouté 2017-11-19 Anthony Brochu
                                    );

            if (laRecherche.noTypeActiviteRecherche != null)
            {
                membresTrouves = membresTrouves
                                 .Where(m => m.listeHobbies.Select(t => t.noType).Contains((int)laRecherche.noTypeActiviteRecherche));
            }

            if (laRecherche.noTypeInterets != null)
            {
                membresTrouves = membresTrouves
                                 .Where(m => m.listeHobbies.Select(t => t.noHobbie).Contains((int)laRecherche.noTypeInterets));
            }
            #endregion

            return(membresTrouves);
        }
 public void DbFunctionsTests_AddYears_DateTimeOffset_Test()
 {
     this.AssertException <NotSupportedException>(() => {
         this.GetOrderQuery().Select(x => DbFunctions.AddYears(this.TestDateTimeOffset, 1)).First();
     });
 }
Example #15
0
        public Tuple <IEnumerable <CandidateDTO>, int> Get(
            string firstName,
            string lastName,
            bool?relocationAgreement,
            bool?isMale,
            int?minAge,
            int?maxAge,
            DateTime?startExperience,
            int?minSalary,
            int?maxSalary,
            int?currencyId,
            int?industryId,
            string position,
            string technology,
            IEnumerable <LanguageSkillDTO> languageSkills,
            IEnumerable <int> citiesIds,
            int current, int size)
        {
            var filters = new List <Expression <Func <Candidate, bool> > >();

            if (!String.IsNullOrEmpty(firstName))
            {
                filters.Add(x => x.FirstName.ToLower().StartsWith(firstName.ToLower()));
            }
            if (!String.IsNullOrEmpty(lastName))
            {
                filters.Add(x => x.LastName.ToLower().StartsWith(lastName.ToLower()));
            }
            if (relocationAgreement.HasValue)
            {
                filters.Add(x => x.RelocationAgreement == relocationAgreement.Value);
            }
            if (isMale.HasValue)
            {
                filters.Add(x => x.IsMale.Value == isMale.Value);
            }
            if (minAge.HasValue)
            {
                if (maxAge.HasValue)
                {
                    filters.Add(x => x.BirthDate.Value <= DbFunctions.AddYears(DateTime.Now, -minAge.Value) && x.BirthDate.Value >= DbFunctions.AddYears(DateTime.Now, -maxAge.Value));
                }
            }
            if (startExperience.HasValue)
            {
                filters.Add(x => x.StartExperience <= startExperience.Value);
            }
            if (minSalary.HasValue)
            {
                if (maxSalary.HasValue)
                {
                    filters.Add(x => x.SalaryDesired >= minSalary.Value && x.SalaryDesired <= maxSalary.Value);
                }
            }
            if (currencyId.HasValue)
            {
                filters.Add(x => x.CurrencyId == currencyId.Value);
            }
            if (industryId.HasValue)
            {
                filters.Add(x => x.IndustryId == industryId);
            }
            if (!String.IsNullOrEmpty(position))
            {
                filters.Add(cand => cand.PositionDesired.ToLower().StartsWith(position.ToLower()));
            }
            if (!String.IsNullOrEmpty(technology))
            {
                filters.Add(x => x.Skills.Any(s => s.Title.StartsWith(technology) || x.Tags.Any(t => t.Title.StartsWith(technology))));
            }
            if (citiesIds.Any())
            {
                filters.Add(x => citiesIds.Any(y => y == x.CityId));
            }
            if (languageSkills.Any())
            {
                foreach (var ls in languageSkills)
                {
                    if (ls.LanguageLevel.HasValue)
                    {
                        filters.Add(x => x.LanguageSkills.Any(l => l.LanguageId == ls.LanguageId && l.LanguageLevel.Value >= ls.LanguageLevel.Value));
                    }
                    else
                    {
                        filters.Add(x => x.LanguageSkills.Any(l => l.LanguageId == ls.LanguageId));
                    }
                }
            }
            var candidates = uow.CandidateRepo.Get(filters);
            var total      = candidates.Count();

            return(new Tuple <IEnumerable <CandidateDTO>, int>(
                       candidates.Skip(current * size).Take(size).Select(candidate => DTOService.ToDTO <Candidate, CandidateDTO>(candidate)),
                       total));
        }
        public IEnumerable <PayingItem> GetPayingItemsForLastYear(WebUser user)
        {
            var dateFrom = DateTime.Parse(DateTime.Today.ToString("Y", CultureInfo.CurrentCulture));

            try
            {
                return(_payingItemService.GetList(x => x.UserId == user.Id && x.Date <= DbFunctions.AddMonths(dateFrom, 1) && x.Date >= DbFunctions.AddYears(dateFrom, -1))
                       .ToList());
            }
            catch (ServiceException e)
            {
                throw new WebUiHelperException(
                          $"Ошибка в типе {nameof(ReportControllerHelper)} в методе {nameof(GetPayingItemsForLastYear)}", e);
            }
        }