예제 #1
0
        public async Task <T> Create(T entity)
        {
            using (FoodFightDbContext context = _dBContextFactory.CreateDbContext())
            {
                EntityEntry <T> createdResult = await context.Set <T>().AddAsync(entity);

                await context.SaveChangesAsync();

                return(createdResult.Entity);
            }
        }
예제 #2
0
        internal static IMLOpsDbContext CreateDbContext()
        {
            var configuration = ConfigurationFactory.GetConfiguration();

            var options = new DbContextOptionsBuilder()
                          .UseCosmos(configuration[ConfigurationKeys.CosmosEndPoint],
                                     configuration[ConfigurationKeys.CosmosAccountKey], "MLOpsNET")
                          .Options;

            var contextFactory = new DbContextFactory(options, CosmosEntityConfigurator.OnModelCreating);
            var context        = contextFactory.CreateDbContext();

            return(contextFactory.CreateDbContext());
        }
예제 #3
0
 /// <summary>
 /// 获取所有角色(role)
 /// </summary>
 /// <returns></returns>
 public List <dictionary> GetAllRole(int page, int limit)
 {
     using (IDbContext dbContext = DbContextFactory.CreateDbContext())
     {
         return(dbContext.Query <dictionary>().Where(p => p.key.Equals("角色")).TakePage(page, limit).ToList());
     }
 }
        private async Task ProcessCategory(KeyValuePair <string, JToken> item)
        {
            var podId    = item.Key;
            var catArray = JArray.Parse(item.Value.ToString());
            var podcast  = GetPodcast(podId);

            if (podcast != null)
            {
                Logger.LogInformation("********Updating: " + podcast.Title);
                Parallel.ForEach(catArray, cat =>
                {
                    var podcastCategory = new PodcastCategory
                    {
                        CategoryId = Convert.ToInt32(cat, CultureInfo.InvariantCulture), PodcastId = podcast.Id
                    };

                    using (var innerContext = DbContextFactory.CreateDbContext())
                    {
                        var exists = PodcastCategoryExists(podcastCategory);
                        if (exists == null)
                        {
                            Categories.Add(podcastCategory);
                        }
                    }
                });
            }

            if (Categories.Any())
            {
                Categories.AddRange(Categories);
            }
        }
        private async Task DiscordOnMessageReceived(SocketMessage arg)
        {
            if (!arg.Author.IsBot && !arg.Author.IsWebhook)
            {
                lordiscordbotContext context = _factory.CreateDbContext();
                bool userFound = false;
                foreach (User contextUser in context.Users.AsQueryable()
                         .Where(contextUser => contextUser.MemberId == (long)arg.Author.Id))
                {
                    userFound = true;
                    contextUser.MessageCount += 1;
                    break;
                }

                if (!userFound)
                {
                    context.Users.Add(new User
                    {
                        DiscordName  = arg.Author.Username,
                        MemberId     = (long)arg.Author.Id,
                        MessageCount = 1
                    });
                }

                await context.SaveChangesAsync();

                await context.DisposeAsync();
            }
        }
예제 #6
0
 public int GetUser_ListCount()
 {
     using (IDbContext dbContext = DbContextFactory.CreateDbContext())
     {
         return(dbContext.Query <User_List>().Where(p => p.pk_User > 0).Count());
     }
 }
예제 #7
0
        public BaseResult Add(users model)
        {
            BaseResult result          = BaseResult.Fail();
            DateTime   currentDatetime = DateTime.Now;

            using (IDbContext dbContext = DbContextFactory.CreateDbContext())
            {
                try
                {
                    dbContext.Session.BeginTransaction();
                    dbContext.Insert <users>(() => new users()
                    {
                        name     = model.name,
                        username = model.username,
                        password = model.password,
                        role     = model.role,
                        addtime  = model.addtime,
                        state    = model.state,
                    });
                    dbContext.Session.CommitTransaction();
                    result.code = 0;
                    result.msg  = "添加成功";
                    //记录操作日志
                }
                catch (Exception ex)
                {
                    dbContext.Session.RollbackTransaction();
                    //log.Error(ex);
                    //记录日志 ex.Message
                    result.code = -2;
                    result.msg  = "添加失败,发生错误";
                }
            }
            return(result);
        }
예제 #8
0
 public int GetUsersCount()
 {
     using (IDbContext dbContext = DbContextFactory.CreateDbContext())
     {
         return(dbContext.Query <users>().Where(p => p.id > 0).Count());
     }
 }
예제 #9
0
 public List <effect> GetAllEffects()
 {
     using (IDbContext dbContext = DbContextFactory.CreateDbContext())
     {
         return(dbContext.Query <effect>().Where(p => p.id > 0).ToList());
     }
 }
예제 #10
0
 /// <summary>
 /// 所有功能数据
 /// </summary>
 /// <returns></returns>
 public List <effect> GetAllEffects(int page, int limit)
 {
     using (IDbContext dbContext = DbContextFactory.CreateDbContext())
     {
         return(dbContext.Query <effect>().Where(p => p.id > 0).TakePage(page, limit).ToList());
     }
 }
예제 #11
0
 /// <summary>
 /// 判断是否有对应角色名
 /// </summary>
 /// <param name="name"></param>
 /// <returns></returns>
 public int RepeatEffectName(string name)
 {
     using (IDbContext dbContext = DbContextFactory.CreateDbContext())
     {
         return(dbContext.Query <dictionary>().Where(p => p.value == name).Count());
     }
 }
예제 #12
0
 // public static NLog.Logger log = NLog.LogManager.GetCurrentClassLogger();
 /// <summary>
 /// 删除对应角色(字典)
 /// </summary>
 /// <param name="id"></param>
 public int DelRole(int id)
 {
     using (IDbContext dbContext = DbContextFactory.CreateDbContext())
     {
         return(dbContext.Delete <dictionary>(p => p.id == id));
     }
 }
예제 #13
0
 /// <summary>
 /// 返回对应角色的所有功能
 /// </summary>
 /// <param name="dicvalue"></param>
 /// <returns></returns>
 public List <view_users_relevance> GetAllEffectByValue(string dicvalue)
 {
     using (IDbContext dbContext = DbContextFactory.CreateDbContext())
     {
         return(dbContext.Query <view_users_relevance>().Where(p => p.dicvalue == dicvalue).ToList());
     }
 }
예제 #14
0
 public List <dictionary> GetRole()
 {
     using (IDbContext dbContext = DbContextFactory.CreateDbContext())
     {
         return(dbContext.Query <dictionary>().Where(p => p.id > 0).ToList());
     }
 }
예제 #15
0
 public int GetRoleCount()
 {
     using (IDbContext dbContext = DbContextFactory.CreateDbContext())
     {
         return(dbContext.Query <dictionary>().Where(p => p.key.Equals("角色")).Count());
     }
 }
예제 #16
0
 /// <summary>
 /// 返回对应用户的数据
 /// </summary>
 /// <param name="id"></param>
 /// <returns></returns>
 public users GetSingleUsers(int id)
 {
     using (IDbContext dbContext = DbContextFactory.CreateDbContext())
     {
         return(dbContext.Query <users>().Where(p => p.id == id).FirstOrDefault());
     }
 }
예제 #17
0
 /// <summary>
 /// 所有后台用户数据
 /// </summary>
 /// <returns></returns>
 public List <users> GetAllUsers(int page, int limit)
 {
     using (IDbContext dbContext = DbContextFactory.CreateDbContext())
     {
         return(dbContext.Query <users>().Where(p => p.id > 0).OrderByDesc(s => s.addtime).TakePage(page, limit).ToList());
     }
 }
예제 #18
0
 /// <summary>
 /// 判断功能中名称||控制器||动作是否重名
 /// </summary>
 /// <param name="name"></param>
 /// <returns></returns>
 public int RepeatEffectsNameCount(string name)
 {
     using (IDbContext dbContext = DbContextFactory.CreateDbContext())
     {
         return(dbContext.Query <effect>().Where(p => p.name == name).Count());
     }
 }
예제 #19
0
        /// <summary>
        /// 实体查询
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public BaseResult GetEntity(int id)
        {
            BaseResult result = BaseResult.Fail();

            using (IDbContext dbContext = DbContextFactory.CreateDbContext())
            {
                try
                {
                    users entity = dbContext.Query <users>().Where(p => p.id == id).FirstOrDefault();
                    if (entity == null)
                    {
                        result.code = -1;
                        result.msg  = "查询记录失败";
                    }
                    else
                    {
                        result.code = 0;
                        result.data = entity;
                    }
                }
                catch (Exception ex)
                {
                    //log.Error(ex);
                    result.code = -2;
                    result.msg  = "查询发生错误";
                }
            }
            return(result);
        }
예제 #20
0
 public int RepeatEffectsControllersCount(string controllers)
 {
     using (IDbContext dbContext = DbContextFactory.CreateDbContext())
     {
         return(dbContext.Query <effect>().Where(p => p.controllers == controllers).Count());
     }
 }
        public async Task Get_ArrangeDB_SomeData()
        {
            // Arrange: put data directly to the Db.
            var db = _dbContextFactory.CreateDbContext();

            db.Persons.AddRange(
                new Person(0, "FirstName1", "LastName1", null),
                new Person(0, "FirstName2", "LastName2", "MiddleName2"));
            db.SaveChanges();

            // Act
            var persons = await _personsApi.Get();

            // Assert
            persons.Should().HaveCount(2);
        }
예제 #22
0
 public int RepeatEffectsActionCount(string action)
 {
     using (IDbContext dbContext = DbContextFactory.CreateDbContext())
     {
         return(dbContext.Query <effect>().Where(p => p.action == action).Count());
     }
 }
        /// <summary>
        /// Performs some work, either using the peristed context or
        /// by generating a new context for the operation.
        /// </summary>
        /// <param name="work">The work to perform (passed a <see cref="VehicleContext"/>).</param>
        /// <param name="user">The current <see cref="ClaimsPrincipal"/>.</param>
        /// <param name="saveChanges"><c>True</c> to save changes when done.</param>
        /// <returns></returns>
        private async Task WorkInContextAsync(
            Func <VehicleContext, Task> work,
            ClaimsPrincipal user,
            bool saveChanges = false)
        {
            if (PersistedContext != null)
            {
                if (user != null)
                {
                    PersistedContext.User = user;
                }
                // do some work. Save changes flag is ignored because this will be
                // committed later.
                await work(PersistedContext);
            }
            else
            {
                using (var context = _factory.CreateDbContext())
                {
                    context.User = user;
                    await work(context);

                    if (saveChanges)
                    {
                        await context.SaveChangesAsync();
                    }
                }
            }
        }
예제 #24
0
 /// <summary>
 /// 查询对应id的功能
 /// </summary>
 /// <param name="id"></param>
 /// <returns></returns>
 public effect SingleEffect(int id)
 {
     using (IDbContext dbContext = DbContextFactory.CreateDbContext())
     {
         return(dbContext.Query <effect>().Where(p => p.id == id).FirstOrDefault());
     }
 }
예제 #25
0
        private void ExecuteWorkWithSystem(ManagedSystem system,
                                           Action <ManagedSystem> action,
                                           Action <ManagedSystem> onSuccess = null,
                                           Action <ManagedSystem> onFailure = null)
        {
            using var dbContext = DbContextFactory.CreateDbContext();

            try
            {
                dbContext.Entry(system).Reload();

                action(system);

                system.LastAccessed = DateTime.UtcNow;
                onSuccess?.Invoke(system);
            }
            catch (Exception e)
            {
                dbContext.Entry(system).Reload();

                system.AddProblem($"{system.ProblemDescription}\n\n {DateTime.UtcNow}\n{e.Message}".Trim());

                Logger.LogError(e, "While executing work with {system}: {exception}", system.Name, e.Message);

                onFailure?.Invoke(system);

                throw;
            }
            finally
            {
                dbContext.Update(system);
                dbContext.SaveChanges();
            }
        }
예제 #26
0
 public int RepeatUsernameUser(string username)
 {
     using (IDbContext dbContext = DbContextFactory.CreateDbContext())
     {
         return(dbContext.Query <users>().Where(p => p.username == username).Count());
     }
 }
예제 #27
0
        public void DbContextFactoryCreateTests()
        {
            var dbContextFactory = new DbContextFactory();
            var context          = dbContextFactory.CreateDbContext(null);

            Assert.True(context != null);
        }
예제 #28
0
 /// <summary>
 /// 判断是否用户下是否有对应角色
 /// </summary>
 /// <param name="dicvalue"></param>
 /// <returns></returns>
 public int UserHaveRole(string dicvalue)
 {
     using (IDbContext dbContext = DbContextFactory.CreateDbContext())
     {
         return(dbContext.Query <users>().Where(p => p.role == dicvalue).Count());
     }
 }
예제 #29
0
        public virtual async Task CreateAsync(User user, bool orUpdate = false, CancellationToken cancellationToken = default)
        {
            await using var dbContext = DbContextFactory.CreateDbContext();
            var existingUser = (User?)null;

            var supportTransactions = !dbContext.Database.IsInMemory();

            await using var tx = supportTransactions
                ? await dbContext.Database.BeginTransactionAsync(cancellationToken)
                : null;

            var userId = user.Id;

            if (orUpdate)
            {
                existingUser = await dbContext.Users.FindAsync(new [] { (object)userId }, cancellationToken);

                if (existingUser != null)
                {
                    dbContext.Users.Update(user);
                }
            }
            if (existingUser == null)
            {
                dbContext.Users.Add(user);
            }
            await dbContext.SaveChangesAsync(cancellationToken).ConfigureAwait(false);

            await(tx?.CommitAsync(cancellationToken) ?? Task.CompletedTask);
            Invalidate(user, existingUser == null);
        }
예제 #30
0
 /// <summary>
 /// 删除关联对应所有功能
 /// </summary>
 /// <param name="dicvalue"></param>
 public int DelRelevance(string dicvalue)
 {
     using (IDbContext dbContext = DbContextFactory.CreateDbContext())
     {
         return(dbContext.Delete <relevance>(p => p.dicvalue == dicvalue));
     }
 }