当前位置: 首页>>代码示例>>C#>>正文


C# DatabaseContext.SaveChangesAsync方法代码示例

本文整理汇总了C#中DatabaseContext.SaveChangesAsync方法的典型用法代码示例。如果您正苦于以下问题:C# DatabaseContext.SaveChangesAsync方法的具体用法?C# DatabaseContext.SaveChangesAsync怎么用?C# DatabaseContext.SaveChangesAsync使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在DatabaseContext的用法示例。


在下文中一共展示了DatabaseContext.SaveChangesAsync方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: NewQuote

 public async Task<ActionResult> NewQuote(QuoteViewModel vm)
 {
     using (var dbContext = new DatabaseContext())
     {
         var quote = new Quote
         {
             Text = vm.Text,
             Submitter = dbContext.Users.Single(u => u.UserName == User.Identity.Name),
             CreatedAt = DateTime.Now,
             Tags = new List<Tag>()
         };
         var user = dbContext.Users.SingleOrDefault(x => x.UserName == vm.Author);
         if (user != null)
         {
             quote.Author = user;
         }
         else
         {
             quote.AlternateAuthor = String.IsNullOrWhiteSpace(vm.Author) ? "Anonymous" : vm.Author;
         }
         dbContext.Quotes.Add(quote);
         vm = new QuoteViewModel(quote);
         await dbContext.SaveChangesAsync();
         QuotesHub.NewQuote(quote);
     }
     return PartialView("_Quote", vm);
 }
开发者ID:Quantumplation,项目名称:Various.Services,代码行数:27,代码来源:QuotesController.cs

示例2: CreatePoll

        public async Task<IHttpActionResult> CreatePoll(string name)
        {
            using (var dbContext = new DatabaseContext())
            {
                if (string.IsNullOrWhiteSpace(name))
                    return BadRequest().WithReason("A name is required");

                var exists = await GetPolls(dbContext, DateTime.Now)
                    .AnyAsync(p => p.Name == name);
                if (exists)
                    return StatusCode(HttpStatusCode.Conflict)
                        .WithReason("A poll with the same name already exists");

                var currentUser = await dbContext.Users.SingleAsync(u => u.UserName == User.Identity.Name);
                var poll = new LunchPoll
                {
                    Name = name,
                    Date = DateTime.Now,
                    Voters = new List<User>(),
                    Votes = new List<LunchVote>()
                };
                dbContext.LunchPolls.Add(poll);
                await AddToPoll(dbContext, poll, currentUser);
                await dbContext.SaveChangesAsync();

                LunchHub.OnPollChanged(new LunchPollViewModel(poll));
                return Ok();
            }
        }
开发者ID:Quantumplation,项目名称:Various.Services,代码行数:29,代码来源:LunchApi.cs

示例3: UpdateCleverscriptVariables

        public async Task<IHttpActionResult> UpdateCleverscriptVariables(int HitchBotId)
        {
            using (var db = new DatabaseContext())
            {
                var location = await db.Locations.Where(l => l.HitchBotId == HitchBotId && l.LocationProvider == LocationProvider.SpotGPS).OrderByDescending(l => l.TakenTime).FirstAsync();
                var weatherApi = new WeatherHelper.OpenWeatherApi();

                weatherApi.LoadWeatherData(location.Latitude, location.Longitude);

                var contextpacket = new ContextPacket()
                {
                    HitchBotId = HitchBotId,
                    Variables = new List<VariableValuePair>()
                };

                contextpacket.Variables.Add(weatherApi.GetCityNamePair());
                contextpacket.Variables.Add(weatherApi.GetTempFPair());
                contextpacket.Variables.Add(weatherApi.GetTempTextFPair());
                contextpacket.Variables.Add(weatherApi.GetWeatherStatusPair());

                BucketListHelper.GetBucketList(db, HitchBotId, location).ForEach(l => contextpacket.Variables.Add(l));
                BucketListHelper.GetBucketFutureList(db, HitchBotId, location).ForEach(l => contextpacket.Variables.Add(l));
                BucketListHelper.GetBucketPastList(db, HitchBotId, location).ForEach(l => contextpacket.Variables.Add(l));
                BucketListHelper.GetContentList(db, HitchBotId, location).ForEach(l => contextpacket.Variables.Add(l));

                db.ContextPackets.Add(contextpacket);

                await db.SaveChangesAsync();

                return Ok("Variables were updated successfully");
            }
        }
开发者ID:ElrHolis,项目名称:hitchBOT,代码行数:32,代码来源:HitchBotController.cs

示例4: AddPairToHb

        public async Task<IHttpActionResult> AddPairToHb(int HitchBotId, string key, string value)
        {
            if (string.IsNullOrWhiteSpace(key) || string.IsNullOrWhiteSpace(value))
                return BadRequest("One or more of the parameters was null or whitespace.");

            using (var db = new DatabaseContext())
            {
                var packets =
                    await db.ContextPackets.Where(l => l.HitchBotId == HitchBotId)
                        .OrderByDescending(l => l.TimeCreated)
                        .FirstOrDefaultAsync();

                if (packets == null)
                {
                    BadRequest(string.Format("No cleverscript variables found for hitchBOT with ID: {0}.", HitchBotId));
                }

                db.VariableValuePairs.Add(new VariableValuePair()
                {
                    key = key,
                    value = value,
                    ContextPacketId = packets.Id
                });

                await db.SaveChangesAsync();
            }
            return Ok();
        }
开发者ID:ElrHolis,项目名称:hitchBOT,代码行数:28,代码来源:HitchBotController.cs

示例5: NumbersModule

        public NumbersModule(DatabaseContext dbContext)
            : base("/numbers")
        {
            Get["/{id:long}/calls"] = c =>
              {
            long id = c["id"];
            return Negotiate.WithModel(dbContext.Calls.Where(o=>o.NumberId == id).OrderByDescending(o=>o.StartTime).ToArray()).WithView("Calls");
              };

              Get["/"] = _ => Negotiate.WithModel(dbContext.Numbers.ToArray()).WithView("Index");

              Get["/{id:long}/edit"] = c => {
            long id = c["id"];
            Context.ViewBag.ValidationErrors = new Dictionary<string, string>();
            var model = dbContext.Numbers.First(n => n.Id == id);
            return Negotiate.WithModel(new Models.Number {
               Id = model.Id,
               AreaCode = model.AreaCode,
               BusinessNumber = model.BusinessNumber.Substring(2)
            }).WithView("Edit");
              };

              Delete["/{id:long}", true] = async (c, t) => {
            long id = c["id"];
            var number = dbContext.Numbers.First(n => n.Id == id);
            dbContext.Numbers.Remove(number);
            await dbContext.SaveChangesAsync();
            return "";
              };

              Post["/{id:long}", true] = async (c, t) => {
            Context.ViewBag.ValidationErrors = new Dictionary<string, string>();
            var number = this.Bind<Models.Number>();
            long id = c["id"];
            var model = dbContext.Numbers.First(n => n.Id == id);
            try
            {
              model.BusinessNumber = number.BusinessNumber;
              await dbContext.SaveChangesAsync();
              return Response.AsRedirect("/numbers");
            }
            catch (DbEntityValidationException vex)
            {
              Context.ViewBag.ValidationErrors = vex.EntityValidationErrors.First().ValidationErrors.ToDictionary(v => v.PropertyName, v =>v. ErrorMessage);
            }
            catch (Exception ex)
            {
              Context.ViewBag.Error = ex.Message;
            }
            return Negotiate.WithModel(number).WithView("Edit");
              };

              Get["/new"] = _ =>
              {
            Context.ViewBag.ValidationErrors = new Dictionary<string, string>();
            return Negotiate.WithModel(new Models.Number()).WithView("New");
              };

              Post["/", true] = async (_, t) =>
              {
            Context.ViewBag.ValidationErrors = new Dictionary<string, string>();
            var number = this.Bind<Models.Number>();
            try
            {
              var availableNumber = (await AvailableNumber.SearchLocal(new Dictionary<string, object> { { "areaCode", number.AreaCode.Substring(1, 3) }, { "quantity", 1 } })).FirstOrDefault();
              if (availableNumber == null)
              {
            throw new Exception("Missing available phone number");
              }
              var createdNumber = await PhoneNumber.Create(new Dictionary<string, object> { { "number", availableNumber.Number}, { "applicationId", Context.Items["applicationId"] as string } });
              number.BwId = createdNumber.Id;
              number.TrackingNumber = availableNumber.Number;
              try
              {
            dbContext.Numbers.Add(number);
            await dbContext.SaveChangesAsync();
            return Response.AsRedirect("/numbers");
              }
              catch (DbEntityValidationException vex)
              {
            Context.ViewBag.ValidationErrors = vex.EntityValidationErrors.First().ValidationErrors.ToDictionary(v => v.PropertyName, v => v.ErrorMessage);
              }
            }
            catch(Exception ex)
            {
              Trace.WriteLine(ex.ToString());
              Context.ViewBag.Error = "There was a problem setting up your number. Try again.";
            }
            return Negotiate.WithModel(number).WithView("New");
              };
        }
开发者ID:BandwidthExamples,项目名称:csharp-call-tracking,代码行数:91,代码来源:NumbersModule.cs

示例6: CallbackModule

        public CallbackModule(DatabaseContext dbContext)
        {
            Get["/callback", true] = async (_, t) =>
              {
            try
            {
              dynamic ev = Request.Query;
              var to = (string)ev.To;
              var callId = (string)ev.CallId;
              Call call;
              Trace.WriteLine(Request.Url.ToString());
              switch ((string)ev.EventType)
              {
            case "answer":
              var number = dbContext.Numbers.FirstOrDefault(n => n.TrackingNumber == to);
              if (number == null)
              {
                return "";
              }
              call = dbContext.Calls.FirstOrDefault(n => n.CallId == callId);
              if (call == null)
              {
                var time = (string)ev.Time;
                call = new Call
                {
                  CallId = callId,
                  NumberId = number.Id,
                  To = to,
                  From = ev.From,
                  ForwardedTo = number.BusinessNumber,
                  State = "ringing",
                  StartTime = DateTime.Parse(time)
                };
                dbContext.Calls.Add(call);
                await dbContext.SaveChangesAsync();
              }
              var xml = new Bandwidth.Net.Xml.Response(new Bandwidth.Net.Xml.Verbs.Transfer
              {
                TransferTo = number.BusinessNumber,
                TransferCallerId = ev.To,
                RequestUrl = "/callback"
              }).ToXml();
              Trace.WriteLine(xml);
              return Response.AsText(xml, "text/xml");
            case "transferComplete":
              call = dbContext.Calls.First(n => n.CallId == callId);
              call.EndTime = ev.Time;
              if (call.StartTime != null)
              {
                call.CallDuration = (call.EndTime.Value - call.StartTime.Value).TotalSeconds;
                call.State = "completed";
              }
              await dbContext.SaveChangesAsync();
              break;
            case "hangup":
              call = dbContext.Calls.FirstOrDefault(n => n.CallId == callId);
              if (call != null)
              {
                if (call.State != "completed")
                {
                  call.State = "completed";
                }

              }
              await dbContext.SaveChangesAsync();
              break;
              }
            }
            catch (Exception ex)
            {
              Trace.WriteLine(ex.ToString());
            }
            return "";
              };
        }
开发者ID:BandwidthExamples,项目名称:csharp-call-tracking,代码行数:75,代码来源:CallbackModule.cs

示例7: ConfirmLink

        public async Task<ActionResult> ConfirmLink(string code, string state, string error)
        {
            if (error != null)
                return View("Error");
            if (state != User.Identity.GetUserId())
                return View("Error");
            using (var db = new DatabaseContext())
            {
                var user = db.Users.Where(x => x.Id == state).SingleOrDefaultAsync();
                var client = new WebClient();
                var clientId = ConfigurationManager.AppSettings["SlackClientId"];
                var clientSecret = ConfigurationManager.AppSettings["SlackSecret"];
                if (clientId == null || clientSecret == null)
                    return View("Error");
                var tokenRaw = client.DownloadString(new Uri($"https://slack.com/api/oauth.access?client_id={clientId}&client_secret={clientSecret}&code={code}"));
                var token = JsonConvert.DeserializeAnonymousType(tokenRaw, new {access_token = "", scope = ""}).access_token;
                (await user).SlackToken = token;
                await db.SaveChangesAsync();

                return RedirectToAction("Manage");
            }
        }
开发者ID:Quantumplation,项目名称:Various.Services,代码行数:22,代码来源:UserController.cs

示例8: Unlink

 public async Task<ActionResult> Unlink()
 {
     using (var db = new DatabaseContext())
     {
         var userId = User.Identity.GetUserId();
         var user = await db.Users.Where(x => x.Id == userId).SingleOrDefaultAsync();
         user.SlackToken = null;
         await db.SaveChangesAsync();
         return RedirectToAction("Manage");
     }
 }
开发者ID:Quantumplation,项目名称:Various.Services,代码行数:11,代码来源:UserController.cs

示例9: JoinPoll

        public async Task<IHttpActionResult> JoinPoll(int id)
        {
            using (var dbContext = new DatabaseContext())
            {
                var currentUser = await dbContext.Users.SingleAsync(u => u.UserName == User.Identity.Name);

                var poll = await GetPoll(dbContext, id);
                if (poll == null) return NotFound().WithReason("No poll found with the given id.");
                if (poll.Date.Date != DateTime.Now.Date)
                    return StatusCode(HttpStatusCode.Forbidden).WithReason("Stop fucking with the past.");

                await AddToPoll(dbContext, poll, currentUser);

                await dbContext.SaveChangesAsync();
                return Ok();
            }
        }
开发者ID:Quantumplation,项目名称:Various.Services,代码行数:17,代码来源:LunchApi.cs

示例10: DeletePoll

        public async Task<IHttpActionResult> DeletePoll(int id)
        {
            using (var dbContext = new DatabaseContext())
            {
                var poll = await GetPoll(dbContext, id);
                if (poll == null)
                    return NotFound();
                dbContext.LunchPolls.Remove(poll);

                LunchHub.OnPollDeleted(id);

                await dbContext.SaveChangesAsync();
                return Ok();
            }
        }
开发者ID:Quantumplation,项目名称:Various.Services,代码行数:15,代码来源:LunchApi.cs

示例11: DeleteOption

        public async Task<IHttpActionResult> DeleteOption(string name)
        {
            using (var dbContext = new DatabaseContext())
            {
                var option = await dbContext.LunchOptions.Where(o => o.Name == name).SingleOrDefaultAsync();
                if (option == null)
                    return NotFound();

                foreach (var poll in GetPolls(dbContext).Where(p => p.Decision.Id == option.Id))
                    poll.Decision = null;
                dbContext.LunchOptions.Remove(option);

                LunchHub.OnOptionDeleted(option.Id);

                await dbContext.SaveChangesAsync();
                return Ok();
            }
        }
开发者ID:Quantumplation,项目名称:Various.Services,代码行数:18,代码来源:LunchApi.cs

示例12: RenameOption

        public async Task<IHttpActionResult> RenameOption(string name, string newName)
        {
            using (var dbContext = new DatabaseContext())
            {
                if (string.IsNullOrWhiteSpace(name) || string.IsNullOrWhiteSpace(newName))
                    return BadRequest().WithReason("Lunch option not specified");
                var oldOption = await dbContext.LunchOptions.Where(o => o.Name == name).SingleOrDefaultAsync();
                if (oldOption == null)
                    return NotFound();

                var newOption = await dbContext.LunchOptions.SingleOrDefaultAsync(o => o.Name == newName);
                if (newOption == null)
                {
                    // easy, literally rename the old option
                    oldOption.Name = newName;
                }
                else
                {
                    // replace all references to the old one with references to the new
                    // this could mess with scores
                    foreach (var poll in GetPolls(dbContext).Where(p => p.Decision.Id == oldOption.Id))
                        poll.Decision = newOption;

                    var oldVotes = await dbContext.LunchVotes
                        .Include(v => v.Poll).Include(v => v.User)
                        .Where(v => v.Option.Id == oldOption.Id)
                        .ToListAsync();
                    var newVotes = await dbContext.LunchVotes
                        .Include(v => v.Poll).Include(v => v.User)
                        .Where(v => v.Option.Id == newOption.Id)
                        .ToDictionaryAsync(v => new { v.Poll, v.User });

                    var toAdd =
                        from old in oldVotes
                        where !newVotes.ContainsKey(new { old.Poll, old.User })
                        select new LunchVote
                        {
                            Poll = old.Poll,
                            User = old.User,
                            Option = newOption,
                            Score = old.Score
                        };

                    dbContext.LunchVotes.AddRange(toAdd);
                    dbContext.LunchVotes.RemoveRange(oldVotes);
                    dbContext.LunchOptions.Remove(oldOption);
                }


                // Refresh all of today's polls in case any scores have changed
                foreach (var poll in GetPolls(dbContext, DateTime.Now))
                    LunchHub.OnPollChanged(new LunchPollViewModel(poll));

                await dbContext.SaveChangesAsync();
                return Ok();
            }
        }
开发者ID:Quantumplation,项目名称:Various.Services,代码行数:57,代码来源:LunchApi.cs

示例13: Decide

        public async Task<IHttpActionResult> Decide(int id, string decision)
        {
            using (var dbContext = new DatabaseContext())
            {
                var poll = await GetPoll(dbContext, id);
                if (poll == null) return NotFound().WithReason("No poll found with the given id.");
                if (string.IsNullOrWhiteSpace(decision)) return BadRequest().WithReason("Lunch option not specified");
                poll.Decision = await GetOrAddOption(dbContext, decision);

                await dbContext.SaveChangesAsync();
                return Ok();
            }
        }
开发者ID:Quantumplation,项目名称:Various.Services,代码行数:13,代码来源:LunchApi.cs

示例14: RemoveFromPoll

        public async Task<IHttpActionResult> RemoveFromPoll(int id, string username)
        {
            using (var dbContext = new DatabaseContext())
            {
                var poll = await GetPoll(dbContext, id);
                if (poll == null) return NotFound().WithReason("No poll found with the given id.");
                var user = await dbContext.Users.SingleOrDefaultAsync(p => p.UserName == username);
                if (user == null) return NotFound().WithReason("No user found with the given name.");

                RemoveFromPoll(dbContext, poll, user);

                await dbContext.SaveChangesAsync();
                return Ok();
            }
        }
开发者ID:Quantumplation,项目名称:Various.Services,代码行数:15,代码来源:LunchApi.cs

示例15: Vote

        public async Task<IHttpActionResult> Vote([FromUri]int id, [FromBody]LunchVoteViewModel vote)
        {
            using (var dbContext = new DatabaseContext())
            {
                if (vote == null)
                    return StatusCode(HttpStatusCode.BadRequest).WithReason("What the fuck are you doing");
                if (vote.Score > 1 || vote.Score < -1)
                    return StatusCode(HttpStatusCode.Forbidden).WithReason("Stop fucking with the votes.");

                var poll = await GetPoll(dbContext, id);
                if (poll == null)
                    return NotFound().WithReason("No poll found with the given id.");
                if (poll.Date.Date != DateTime.Now.Date)
                    return StatusCode(HttpStatusCode.Forbidden).WithReason("Stop fucking with the past.");

                var user = await dbContext.Users.SingleAsync(u => u.UserName == User.Identity.Name);
                if (!poll.Voters.Contains(user))
                    return StatusCode(HttpStatusCode.Forbidden).WithReason("Only members are allowed to vote.");

                if (string.IsNullOrWhiteSpace(vote.Name))
                    return StatusCode(HttpStatusCode.BadRequest).WithReason("Lunch option not specified");
                var option = await GetOrAddOption(dbContext, vote.Name);


                var currentVote = poll.Votes.SingleOrDefault(v => v.User == user && v.Option == option);
                if ((currentVote?.Score ?? 0) == vote.Score)
                {
                    await dbContext.SaveChangesAsync();
                    return Ok();
                }

                if (vote.Score == 0)
                {
                    dbContext.LunchVotes.Remove(currentVote);
                }
                else if (currentVote != null)
                {
                    currentVote.Score = vote.Score;
                }
                else
                {
                    dbContext.LunchVotes.Add(new LunchVote
                    {
                        Poll = poll,
                        Option = option,
                        User = user,
                        Score = vote.Score
                    });
                }
                await dbContext.SaveChangesAsync();

                LunchHub.OnVote(poll.Id, option, poll.Votes.Where(v => v.Option == option));

                return Ok();
            }
        }
开发者ID:Quantumplation,项目名称:Various.Services,代码行数:56,代码来源:LunchApi.cs


注:本文中的DatabaseContext.SaveChangesAsync方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。