Exemplo n.º 1
0
        public void Execute(IJobExecutionContext context)
        {
            Console.WriteLine(" ************  开始执行南航项目:访客撤控 : " + DateTime.Now);
            var db        = new EFContext();
            var dateTime  = DateTime.Now;
            var ApplyList = db.Set <VisitorApply>().Where(p => dateTime > p.VisitEndTime && p.SurveyStatus == "0" && p.DhId != null).ToList();

            foreach (var apply in ApplyList)
            {
                // 闸机Id列表
                var zjids      = db.Set <Relevance>().Where(p => p.SecondKey == apply.BuildingId && p.Name == Relation.GateBuilding).Select(p => p.FirstKey).ToList();
                var channelIds = db.Set <Gate>().Where(t => zjids.Contains(t.Id)).Select(p => p.DeviceNumber + "$7$0$0").ToArray();
                var ResultStr  = DHAccount.CancelSurvey(channelIds, apply.DhId);
                var jo         = ResultStr.Parse2JObject();
                if (jo.Value <bool>("success"))
                {
                    apply.SurveyStatus = "1";
                    Console.WriteLine("撤控成功:" + ResultStr + "  DhId = " + apply.DhId);
                }
                else
                {
                    Console.WriteLine("撤控失败:" + ResultStr + "  DhId = " + apply.DhId);
                }
                if (apply.VisitType == "1")
                {
                    Console.WriteLine("校外访客删除:" + DHAccount.PUSH_DH_DELETE_PERSON(new string[] { apply.DhId }));
                }
            }
            db.SaveChanges();
            db.Dispose();
        }
Exemplo n.º 2
0
        /// <summary>
        /// Step1: 统计未归报表
        /// </summary>
        /// <param name="QuartzTime"></param>
        /// <param name="moudle"></param>
        /// <param name="TableName"></param>
        public void ProcessNoReturnException(DateTime QuartzTime, string TableName, List <string> LeaveListId, EFContext db)
        {
            //查看所有人员当天的最后一条记录
            var StartTimestamp     = DateHelper.ConvertDateTimeInt(QuartzTime.AddDays(-1));
            var EndTimestamp       = DateHelper.ConvertDateTimeInt(QuartzTime);
            var UsersLastRecordSql = "select b.id,b.code,b.inout, b.swipDate, b.date,b.firstName name from (SELECT code, MAX(swipDate) swipDate FROM [dbo].[" + TableName + "] GROUP BY code HAVING MAX(swipDate) BETWEEN '" + StartTimestamp + "' and '" + EndTimestamp + "' ) a JOIN " + TableName + " b on a.code=b.code and a.swipDate = b.swipDate";
            var List       = SqlHelper.ExecuteDataTable(UsersLastRecordSql).ToJson().Deserialize <List <LastRecordMoudle> >().Where(p => p.inout == 1 && !LeaveListId.Contains(p.studentId)).ToList();
            var ReportList = new List <NoReturnReport>();

            foreach (var noReturn in List)
            {
                var IdAndClass = db.Set <Student>().Where(s => s.StudentNumber.Equals(noReturn.code)).FirstOrDefault();
                if (IdAndClass == null)
                {
                    continue;
                }
                var report = new NoReturnReport();
                report.Id          = Guid.NewGuid().ToString().Replace("-", "");
                report.CreatedTime = QuartzTime.AddDays(-1).Date;
                report.College     = "root";
                report.Account     = noReturn.code;
                report.OutTime     = DateHelper.GetTime(noReturn.swipDate);
                report.Name        = noReturn.name;
                report.StudentId   = IdAndClass.Id;
                report.ClassId     = IdAndClass.ClassId;
                report.DormId      = db.Set <DormStudent>().Where(s => s.StudentId.Equals(IdAndClass.Id)).Select(u => u.DormId).FirstOrDefault();
                report.DayCount    = (decimal)DateHelper.DateDiff("hour", DateHelper.GetTime(noReturn.swipDate), QuartzTime);
                ReportList.Add(report);
            }
            db.Set <NoReturnReport>().AddRange(ReportList);
            db.SaveChanges();
            Console.WriteLine(" **********  未归人员数量:" + ReportList.Count());
        }
        public void Delete(Guid id)
        {
            var obj = _ctx.Set <T>().Find(id);

            _ctx.Set <T>().Remove(obj);
            _ctx.SaveChanges();
        }
Exemplo n.º 4
0
        /// <summary>
        /// 简化程序(把教师数据分为四张表,分为四个方法进行) Sys_User
        /// </summary>
        /// <param name="db"></param>
        /// <param name="newData"></param>
        public void ProcessSchoolTeacherSysUser(EFContext db, NHModel newDb)
        {
            var newData = newDb.Set <TeacherInfo>().AsNoTracking().Select(p => new UserMoudle
            {
                Id          = p.teacherId,
                Name        = p.teacherName,
                Account     = p.LoginId,
                OrganId     = p.orgId,
                MobilePhone = p.teacherPhone,
                HeadIcon    = p.ImgUri,
                Gender      = p.sex ? "1" : "0"
            }).ToList();
            var oldData = db.Set <User>().AsNoTracking().Select(p => new UserMoudle
            {
                Id          = p.Id,
                Name        = p.Name,
                Account     = p.Account,
                OrganId     = p.OrganId,
                MobilePhone = p.MobilePhone,
                HeadIcon    = p.HeadIcon,
                Gender      = p.Gender == true ? "1" : "0"
            }).ToList();
            var addList    = newData.Except(oldData).ToList();
            var Ids        = oldData.Select(p => p.Id).ToList();
            var InsertList = new List <User>();

            foreach (var tea in addList)
            {
                if (Ids.Contains(tea.Id))
                {
                    db.Set <User>().Where(p => p.Id.Equals(tea.Id)).Update(p => new User
                    {
                        Name        = tea.Name,
                        Account     = tea.Account,
                        OrganId     = tea.OrganId,
                        MobilePhone = tea.MobilePhone,
                        DutyId      = "teacherDuty",
                        Gender      = tea.Gender == "1" ? true : false
                    });
                }
                else
                {
                    InsertList.Add(new User()
                    {
                        DutyId      = "teacherDuty",
                        Id          = tea.Id,
                        Name        = tea.Name,
                        Account     = tea.Account,
                        OrganId     = tea.OrganId,
                        MobilePhone = tea.MobilePhone,
                        HeadIcon    = tea.HeadIcon,
                        Gender      = tea.Gender == "1" ? true : false
                    });
                }
            }
            db.Set <User>().AddRange(InsertList);
            db.SaveChanges();
        }
        public void Delete(int id)
        {
            var entity = GetById(id);

            if (entity != null)
            {
                _ctx.Set <T>().Remove(entity);
            }
        }
Exemplo n.º 6
0
 public void Excluir(Func <T, bool> predicate)
 {
     using (contexto = new EFContext())
     {
         contexto.Set <T>()
         .Where(predicate).ToList()
         .ForEach(del => contexto.Set <T>().Remove(del));
         contexto.SaveChanges();
     }
 }
Exemplo n.º 7
0
        /// <summary>
        /// 处理同步组织机构信息
        /// </summary>
        public void ProcessOrgInfo(EFContext db)
        {
            Console.WriteLine("开始同步教师组织机构信息: 南航项目 --> " + DateTime.Now.ToLocalTime());
            var sw = new Stopwatch();

            sw.Start();
            //校方数据集(分为两种:修改数据和新增数据)
            var newDb   = new NHModel();
            var newData = newDb.Set <Teacher_Organ>().AsNoTracking().Select(p => new OrganMoudle {
                Id = p.OrgId, Name = p.OrgName, ParentId = p.ParentOrgId, EnCode = p.OrgId
            }).ToList();
            //获取生产环境数据库数据集
            var oldData = db.Set <Org>().AsNoTracking().Select(p => new OrganMoudle {
                Id = p.Id, Name = p.Name, ParentId = p.ParentId, EnCode = p.Code
            }).ToList();
            var addList = newData.Except(oldData).ToList(); //取差集 (新增和修改数据)

            var idList  = oldData.Select(p => p.Id).ToList();
            var endList = new List <Org>();

            foreach (var org in addList)
            {
                if (org.ParentId == null)
                {
                    org.ParentId = "3";
                }
                if (idList.Contains(org.Id))
                {
                    db.Set <Org>().Where(p => p.Id.Equals(org.Id)).Update(p => new Org
                    {
                        ParentId = org.ParentId,
                        Name     = org.Name
                    });
                }
                else
                {
                    endList.Add(new Org()
                    {
                        Id       = org.Id,
                        Name     = org.Name,
                        ParentId = org.ParentId,
                        Code     = org.EnCode
                    });
                }
            }
            //newDb.BulkDelete(newDb.OrganizationInfoes.ToList()); //操作完成后,删除取出来的数据
            //oldDb.BulkInsert(endList);
            db.Set <Org>().AddRange(endList);
            db.SaveChanges();
            newDb.Dispose();
            sw.Stop();
            Console.WriteLine("南航项目:同步组织机构信息结束 --> 合计耗时:" + sw.ElapsedMilliseconds / 1000 + "s");
        }
Exemplo n.º 8
0
        public IActionResult Attack(string ime)
        {
            FormattableString query = $"SELECT * FROM Korisnici WHERE Ime='{ime}' AND Uloga = 'Korisnik'";
            var searchedUsers       = _context.Set <Korisnik>().FromSql(query).ToList();

            return(View("Attack", searchedUsers));
        }
Exemplo n.º 9
0
        /// <summary>
        /// 加载内存数据
        /// </summary>
        public virtual void Load()
        {
            var dbContext = ((IObjectContextAdapter)EFContext.DbContext).ObjectContext;

            dbContext.Refresh(System.Data.Entity.Core.Objects.RefreshMode.ClientWins, EFContext.Set <TEntity>());
            EFContext.Set <TEntity>().Load();
        }
Exemplo n.º 10
0
        public virtual IEnumerable <TEntity> GetEntitiesBySql(string tableName)
        {
            var lt = EFContext.DbContext.Database.SqlQuery <TEntity>(string.Format("select * from {0}", tableName)).ToList();

            EFContext.Set <TEntity>().Load();//加载内存数据?
            return(lt);
        }
Exemplo n.º 11
0
        /// <summary>
        ///     删除所有符合特定表达式的数据
        /// </summary>
        /// <param name="predicate"> 查询条件谓语表达式 </param>
        /// <param name="isSave"> 是否执行保存 </param>
        /// <returns> 操作影响的行数 </returns>
        public virtual OperationResult Delete(Expression <Func <TEntity, bool> > predicate, bool isSave = true)
        {
            PublicHelper.CheckArgument(predicate, "predicate");
            List <TEntity> entities = EFContext.Set <TEntity>().Where(predicate).ToList();

            return(entities.Count > 0 ? Delete(entities, isSave) : new OperationResult(OperationResultType.Error, "没有符合条件的删除数据"));
        }
Exemplo n.º 12
0
        /// <summary>
        ///     删除指定编号的记录
        /// </summary>
        /// <param name="id"> 实体记录编号 </param>
        /// <param name="isSave"> 是否执行保存 </param>
        /// <returns> 操作影响的行数 </returns>
        public virtual int Delete(object id, bool isSave = true)
        {
            Check.NotNull(id, "id");
            TEntity entity = EFContext.Set <TEntity>().Find(id);

            return(entity != null?Delete(entity, isSave) : 0);
        }
Exemplo n.º 13
0
 public virtual IList <T> FindPagenatedList <K>(int pageIndex, int pageSize, Expression <Func <T, bool> > predicate,
                                                Expression <Func <T, K> > keySelector, bool ascending = true)
 {
     return(@ascending
         ? EFContext.Set <T>().Where(predicate).OrderBy(keySelector).Skip((pageIndex - 1) * pageSize).Take(pageSize).AsNoTracking().ToList()
         : EFContext.Set <T>().Where(predicate).OrderByDescending(keySelector).Skip((pageIndex - 1) * pageSize).Take(pageSize).AsNoTracking().ToList());
 }
Exemplo n.º 14
0
        public virtual IList <T> FindPagenatedList <K>(int pageIndex, int pageSize, Expression <Func <T, bool> > predicate,
                                                       string sortProperty, bool ascending = true)
        {
            var q = EFContext.Set <T>().Where(predicate).AsNoTracking();

            return(q.SingleOrderBy(sortProperty, ascending).Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList());
        }
Exemplo n.º 15
0
        public IHttpActionResult PostOrder(OrderCreateVM model)
        {
            if (ModelState.IsValidField(nameof(model.SessionID)))
            {
                var session = _context.Sessions.Find(model.SessionID);
                if (session == null)
                {
                    ModelState.AddModelError(nameof(model.SessionID), "Сеанс не найден");
                }
                else
                {
                    if (session.StartingDate < DateTime.Now.AddMinutes(-30.0))
                    {
                        ModelState.AddModelError(nameof(model.SessionID), "Запись на идущий сеанс запрещена");
                    }
                }
            }
            if (ModelState.IsValid)
            {
                var entityModel = new Order()
                {
                    SessionID = model.SessionID,
                    Count     = model.Count
                };

                _context.Set <Order>().Add(entityModel);
                _context.SaveChanges();

                return(Ok());
            }
            else
            {
                return(BadRequest(ModelState));
            }
        }
Exemplo n.º 16
0
 public async Task <IEnumerable <T> > ReadAsync()
 {
     using (var context = new EFContext())
     {
         return(await context.Set <T>().ToListAsync());
     }
 }
Exemplo n.º 17
0
        /// <summary>
        ///     删除所有符合特定表达式的数据
        /// </summary>
        /// <param name="predicate"> 查询条件谓语表达式 </param>
        /// <param name="isSave"> 是否执行保存 </param>
        /// <returns> 操作影响的行数 </returns>
        public virtual int Delete(Expression <Func <TEntity, bool> > predicate, bool isSave = true)
        {
            PublicHelper.CheckArgument(predicate, "predicate");
            List <TEntity> entities = EFContext.Set <TEntity, TKey>().Where(predicate).ToList();

            return(entities.Count > 0 ? Delete(entities, isSave) : 0);
        }
Exemplo n.º 18
0
 private EFContext contexto;// = new EFContext();
 public IEnumerable <T> ObterTodos()
 {
     using (contexto = new EFContext())
     {
         return(contexto.Set <T>().ToList());
     }
 }
Exemplo n.º 19
0
        /// <summary>
        ///     删除指定编号的记录
        /// </summary>
        /// <param name="id"> 实体记录编号 </param>
        /// <param name="saveNow"> 是否执行保存 </param>
        /// <returns> 操作影响的行数 </returns>
        public virtual int Delete(TKeyType id, bool saveNow = true, bool validateOnSaveEnabled = false)
        {
            PublicHelper.CheckArgument(id, "id");
            TEntity entity = EFContext.Set <TEntity, TKeyType>().Find(id);

            return(entity != null?Delete(entity, saveNow, validateOnSaveEnabled) : 0);
        }
Exemplo n.º 20
0
        /// <summary>
        ///     删除指定编号的记录
        /// </summary>
        /// <param name="id"> 实体记录编号 </param>
        /// <param name="isSave"> 是否执行保存 </param>
        /// <returns> 操作影响的行数 </returns>
        public virtual int Delete(TKey id, bool isSave = true)
        {
            PublicHelper.CheckArgument(id, "id");
            TEntity entity = EFContext.Set <TEntity, TKey>().Find(id);

            return(entity != null?Delete(entity, isSave) : 0);
        }
Exemplo n.º 21
0
        public RepositoryBase()
        {
            Context = new EFContext();

            //İlgili DbSet'i Table'a atadık.
            Table = Context.Set <T>();
        }
Exemplo n.º 22
0
        /// <summary>
        ///     删除所有符合特定表达式的数据
        /// </summary>
        /// <param name="predicate"> 查询条件谓语表达式 </param>
        /// <param name="saveNow"> 是否执行保存 </param>
        /// <returns> 操作影响的行数 </returns>
        public virtual int Delete(Expression <Func <TEntity, bool> > predicate, bool saveNow = true, bool validateOnSaveEnabled = false)
        {
            PublicHelper.CheckArgument(predicate, "predicate");
            List <TEntity> entities = EFContext.Set <TEntity, TKeyType>().Where(predicate).ToList();

            return(entities.Count > 0 ? Delete(entities, saveNow, validateOnSaveEnabled) : 0);
        }
Exemplo n.º 23
0
        public static string NotOutTime         = "24"; //长时间未出  最近的一次打卡记录为进入宿舍且24小时内没有外出打卡记录
        public void Execute(IJobExecutionContext context)
        {
            // 测试用时间点
            //DateTime QuartzTime = Convert.ToDateTime("2019-05-24 02:00:00");
            var QuartzTime = DateTime.Now;
            var TableName  = "DHFLOW_" + QuartzTime.Year + QuartzTime.Month.ToString().PadLeft(2, '0');
            var db         = new EFContext();
            var sw         = new Stopwatch();

            sw.Start();

            Console.WriteLine("南航项目:开始统计请假学生列表 --> " + DateTime.Now.ToLocalTime());
            //过滤:请假的人员
            var EndTime     = QuartzTime.Date.AddDays(-1).AddHours(23);
            var LeaveListId = db.Set <LeaveOrder>().Where(p => p.EndOfTime > EndTime).Select(p => p.LeaveerId).ToList();

            Console.WriteLine("南航项目:开始统计未归报表 --> " + DateTime.Now.ToLocalTime());
            //Step1  统计未归报表
            ProcessNoReturnException(QuartzTime, TableName, LeaveListId, db);
            sw.Stop();
            Console.WriteLine("南航项目:统计未归报表 --> 合计耗时:" + sw.ElapsedMilliseconds / 1000 + "s");
            sw.Restart();
            Console.WriteLine("南航项目:开始统计晚归报表 --> " + DateTime.Now.ToLocalTime());
            //Step2 统计晚归报表
            ProcessLateReturnException(QuartzTime, TableName, LeaveListId, db);
            sw.Stop();
            Console.WriteLine("南航项目:统计晚归报表 --> 合计耗时:" + sw.ElapsedMilliseconds / 1000 + "s");
            sw.Restart();
            Console.WriteLine("南航项目:开始统计长时间未出报表 --> " + DateTime.Now.ToLocalTime());
            //Step3: 统计长时间未出报表
            ProcessNotOutException(QuartzTime, TableName, db);
            sw.Stop();
            Console.WriteLine("南航项目:统计长时间未出报表 --> 合计耗时:" + sw.ElapsedMilliseconds / 1000 + "s");
        }
Exemplo n.º 24
0
        public List <UserItemViewModel> GetUsers()
        {
            Thread.Sleep(1500);
            var el    = _context.Set <DbUser>().FirstOrDefault(s => s.Email == "*****@*****.**");
            var model = new List <UserItemViewModel>
            {
                new UserItemViewModel
                {
                    Id    = 1, Email = "*****@*****.**", Image = "https://cdn.pixabay.com/photo/2017/07/28/23/34/fantasy-picture-2550222_960_720.jpg", Age = 30, Phone = "+380957476156", Description = "PHP programmer",
                    Roles = new List <RoleItemViewModel>
                    {
                        new RoleItemViewModel {
                            Id = 2, Name = "Admin"
                        }
                    }
                },
                new UserItemViewModel
                {
                    Id    = 2, Email = "*****@*****.**", Image = "https://avatars.mds.yandex.net/get-zen_doc/1362253/pub_5c1f1fbcee97de00aacce7d3_5c1f22b738ad6b00a9ecba7f/scale_600", Age = 40, Phone = "+380957476999", Description = ".NET programmer",
                    Roles = new List <RoleItemViewModel>
                    {
                        new RoleItemViewModel {
                            Id = 2, Name = "Admin"
                        },
                        new RoleItemViewModel {
                            Id = 3, Name = "Meson"
                        }
                    }
                }
            };

            return(model);
        }
Exemplo n.º 25
0
        public virtual int Delete(TKey key, bool isSave = true)
        {
            TEntity entity = EFContext.Set <TEntity, TKey>().Find(key);

            EFContext.RegisterDeleted <TEntity, TKey>(entity);
            return(isSave ? EFContext.Submit() : 0);
        }
Exemplo n.º 26
0
        public virtual void Add(TEntity entity)
        {
            EFContext.Set <TEntity>().Add(entity);
            var entry = EFContext.DbContext.Entry(entity);

            entry.State = System.Data.Entity.EntityState.Added;  //一直有问题不可以
            entry.Reload();
        }
Exemplo n.º 27
0
 public void Gravar(T entidade)
 {
     using (contexto = new EFContext())
     {
         contexto.Set <T>().Add(entidade);
         this.SalvarMundancas();
     }
 }
Exemplo n.º 28
0
        /// <summary>
        ///     删除指定编号的记录
        /// </summary>
        /// <param name="id"> 实体记录编号 </param>
        /// <param name="isSave"> 是否执行保存 </param>
        /// <returns> 操作影响的行数 </returns>
        public virtual DataResult Delete(object id, bool isSave = true)
        {
            TEntity entity = EFContext.Set <TEntity, TKey>().Find(id);

            return(entity != null?Delete(entity, isSave) : null);

            //return 0;
        }
Exemplo n.º 29
0
 /// <inheritdoc />
 /// <summary>
 ///     删除实体记录集合
 /// </summary>
 /// <param name="entities"> 实体记录集合 </param>
 /// <param name="isSave"> 是否执行保存 </param>
 /// <returns> 操作影响的行数 </returns>
 public virtual int Delete(IEnumerable <TEntity> entities, bool isSave = true)
 {
     PublicHelper.CheckArgument(entities, "entities");
     //EFContext.RegisterDeleted<TEntity, TKey>(entities);
     //ef 6.0新增方法
     EFContext.Set <TEntity, TKey>().RemoveRange(entities);
     return(isSave ? EFContext.Commit() : 0);
 }
Exemplo n.º 30
0
        public virtual async Task CreateAsync(T item)
        {
            if (item == null)
            {
                throw new Exception("Значения модели не описаны");
            }
            await _context.Set <T>().AddAsync(item);

            await _context.SaveChangesAsync();
        }
Exemplo n.º 31
0
 private static void InitializeDB()
 {
     console.WriteOutputOnNewLine("\nInitializing the db....");
     using (var ctx = new EFContext())
     {
         var dummyUser = ctx.Set<User>().FirstOrDefault();
     }
     console.WriteOutputOnNewLine("\nInitializing db has been completed....");
 }