// //Кнопка, переносит данные в основную таблицу. // private void Transfer_Button_Click(object sender, EventArgs e) { var archiveEvent = SearchingObject(); var addEventForm = new AddEventForm(); LoadDate_ComboBox(addEventForm); addEventForm.comboBox1.Text = archiveEvent.vCalendar.ToString(); addEventForm.comboBox2.Text = archiveEvent.vListofCases.ToString(); addEventForm.comboBox1.Enabled = false; addEventForm.dateTimePicker1.Value = Convert.ToDateTime(archiveEvent.StartTime); addEventForm.dateTimePicker2.Value = Convert.ToDateTime(archiveEvent.EndTime); DialogResult result = addEventForm.ShowDialog(this); if (result == DialogResult.OK) { try { var eventDate = new EventDate(); eventDate.vListofCases = (ListofCases)addEventForm.comboBox1.SelectedItem; eventDate.vCalendar = (Calendar)addEventForm.comboBox2.SelectedItem; eventDate.StartTime = addEventForm.dateTimePicker1.Value.ToShortTimeString(); eventDate.EndTime = addEventForm.dateTimePicker2.Value.ToShortTimeString(); eventDate.MarkEventSet(); db.DBEventDate.Add(eventDate); db.DBArchiveEvents.Remove(archiveEvent); db.SaveChanges(); MessageBox.Show("Объект восстановлен!", "Оповещение", MessageBoxButtons.OK, MessageBoxIcon.Asterisk); } catch (Exception ex) { MessageBox.Show(ex.Message, ex.Source, MessageBoxButtons.OK, MessageBoxIcon.Error); } } dataGridView1.Refresh(); }
public JsonResult SaveEvent(Event e) { var status = false; if (e.EventID > 0) { //Update the event var v = db.Events.Where(a => a.EventID == e.EventID).FirstOrDefault(); if (v != null) { v.Subject = e.Subject; v.Start = e.Start; v.End = e.End; v.Description = e.Description; v.IsFullDay = e.IsFullDay; v.ThemeColor = e.ThemeColor; } } else { //e.End = DateTime.Now.AddDays(1); //e.Start = DateTime.Now; // e.End = null; db.Events.Add(e); } db.SaveChanges(); status = true; return(new JsonResult { Data = new { status = status } }); }
// //Кнопка, добавляет список выходных. // private void Add_Button_Click(object sender, EventArgs e) { var holiday = new Holidays(); var addHDForm = new AddHolidaysForm(); DialogResult result = addHDForm.ShowDialog(this); try { if (result == DialogResult.OK) { foreach (var item in addHDForm.listBox1.Items) { DateTime date = Convert.ToDateTime(item); holiday.NumDay = date.Day; holiday.NameMonth = String.Format("{0:MMMM}", date); holiday.NumYear = date.Year; db.DBHolidays.Add(holiday); db.SaveChanges(); } dataGridView1.Refresh(); MessageBox.Show("Даты добавлены!", "Оповещение", MessageBoxButtons.OK, MessageBoxIcon.Asterisk); } } catch (Exception ex) { MessageBox.Show(ex.Message, ex.Source, MessageBoxButtons.OK, MessageBoxIcon.Error); } }
public IActionResult Post(Guid rosterId, string code, [FromBody] Shift item) { if (item == null || item.RosterId != rosterId || item.Code != code) { return(BadRequest()); } _context.Shifts.Add(ServerShift.FromShift(item)); _context.SaveChanges(); return(CreatedAtRoute(new { item.RosterId, item.Code }, item)); }
// //Метод, вызываемого события. // private void Config_ToDayIsEvent(EventDate obj, bool flag) { if (flag) { MessageBox.Show($"На сегодня запланировано мероприятие.\r\n{obj.vListofCases.ToString()}", "Уведомление", MessageBoxButtons.OK, MessageBoxIcon.Asterisk); } else if (obj.MarkEventUnset()) { db.SaveChanges(); } }
public IActionResult Post(Guid rosterId, [FromBody] Roster item) { if (item == null || item.Id != rosterId) { return(BadRequest()); } var serverRoster = ServerRoster.FromRoster(item); _context.Rosters.Add(serverRoster); _context.SaveChanges(); return(CreatedAtRoute(new { id = item.Id }, serverRoster)); }
public IActionResult Post(Guid rosterId, string rosterCode, [FromBody] StaffMember item) { if (item == null || item.RosterId != rosterId || item.StaffMemberCode != rosterCode) { return(BadRequest()); } var serverStaffMember = ServerStaffMember.FromStaffMember(item); _context.Staff.Add(serverStaffMember); _context.SaveChanges(); return(CreatedAtRoute(new { item.RosterId, item.StaffMemberCode }, serverStaffMember)); }
public IActionResult Create(int year, string month, int day, int foodId, int mealId) { // TODO PARSE TRY var date = new DateTime(year, int.Parse(month), day); ViewData["Date"] = date; Food food = _calendarDatabase.Foods.Find(foodId); Meal meal = _calendarDatabase.Meals.Find(mealId); if (food == null || meal == null) { TempData["Error"] = "Wrong input"; return(Redirect( string.Format("/calendarFood/add/{0}/{1}/{2}/{3}", year, month, day, mealId))); } // check if already exist and then update it CalendarFoodItem foodItem = _calendarDatabase.FoodItems.Where(cfi => cfi.CalendarDate.Date == date.Date && cfi.Meal.MealID == mealId && cfi.Food.FoodID == food.FoodID).SingleOrDefault(); string GramUnitName = "gram"; WeightType gram = _calendarDatabase.WeightTypes.Where(wt => wt.UnitName == GramUnitName).FirstOrDefault(); if (foodItem == null) { foodItem = new CalendarFoodItem() { Food = food, Meal = meal, Weight = decimal.ToInt32(food.Weight), CalendarDate = date }; _calendarDatabase.FoodItems.Add(foodItem); } else { foodItem.Weight += decimal.ToInt32(food.Weight); } _calendarDatabase.SaveChanges(); TempData["Success"] = "Created."; return(Redirect( string.Format("/calendarFood/add/{0}/{1}/{2}/{3}", year, month, day, mealId))); }
// //Кнопка, заполняет бд. // private void Create_Button_Click(object sender, EventArgs e) { var calendar = new Calendar(); var addCalendarForm = new AddCalendarForm(); var listHolidays = db.DBHolidays.ToList().Select(p => p.FullDate); DialogResult result = addCalendarForm.ShowDialog(this); if (result == DialogResult.OK) { try { DateTime Startdate = addCalendarForm.dateTimePicker1.Value; void AddCalendar(DateTime _date, byte k) { calendar.NumDay = _date.Day; calendar.NameMonth = String.Format("{0:MMMM}", _date); calendar.NumYear = _date.Year; if (k == 1) { calendar.Typeofday = "Выходной день"; } else { calendar.Typeofday = "Рабочий день"; } db.DBCalendars.Add(calendar); } for (int i = 0; i < period; i++) { var date = Startdate.AddDays(i); if (addCalendarForm.ListWeekEnd.Contains(date.DayOfWeek.ToString()) || listHolidays.Contains(string.Format("{0:dd} {0:MMMM} {0:yyyy}", date))) { AddCalendar(date, 1); } else { AddCalendar(date, 0); } db.SaveChanges(); } MessageBox.Show("Календарь создан!", "Оповещение", MessageBoxButtons.OK, MessageBoxIcon.Asterisk); } catch (Exception ex) { MessageBox.Show(ex.Message, ex.Source, MessageBoxButtons.OK, MessageBoxIcon.Error); } } }
public ActionResult Save(int?id, FormCollection actionValues) { var action = new DataAction(actionValues); try { var changedEvent = DHXEventsHelper.Bind <Calendar>(actionValues); switch (action.Type) { case DataActionTypes.Insert: db.Appointments.Add(changedEvent); break; case DataActionTypes.Delete: db.Entry(changedEvent).State = EntityState.Deleted; break; default: // "update" db.Entry(changedEvent).State = EntityState.Modified; break; } db.SaveChanges(); action.TargetId = changedEvent.Id; } catch (Exception) { action.Type = DataActionTypes.Error; } return(new AjaxSaveResponse(action)); }
public ActionResult AddCalendarEvent(string title, string description, string location, string start, string end, string allDay) { int newID; // Convert start and end to DateTime objects DateTime startTime = DateTime.ParseExact(start, "dd-MM-yyyy HH:mm:ss", System.Globalization.CultureInfo.InvariantCulture); DateTime endTime = DateTime.ParseExact(end, "dd-MM-yyyy HH:mm:ss", System.Globalization.CultureInfo.InvariantCulture); // Create CalendarEvent to be passed to database CalendarEvent calEvent = new CalendarEvent { FBID = (String)Session["FBID"], Title = title, Description = description, Location = location, StartTime = startTime, EndTime = endTime, Recurring = false, AllDay = Boolean.Parse(allDay) }; using (CalendarContext db = new CalendarContext()) { // Add CalendarEvent to database db.CalendarEvents.Add(calEvent); db.SaveChanges(); newID = calEvent.EventID; } // Return the new ID value so we can set it on the new calendar object return(Json(newID, JsonRequestBehavior.AllowGet)); }
private void SetUpClient() { var builder = new WebHostBuilder() .UseStartup <CalendarWebApi.Startup>() .ConfigureServices(services => { var context = new CalendarContext(new DbContextOptionsBuilder <CalendarContext>() .UseSqlite("DataSource=:memory:") .EnableSensitiveDataLogging() .Options); services.RemoveAll(typeof(CalendarContext)); services.AddSingleton(context); context.Database.OpenConnection(); context.Database.EnsureCreated(); context.SaveChanges(); // Clear local context cache foreach (var entity in context.ChangeTracker.Entries().ToList()) { entity.State = EntityState.Detached; } }); _server = new TestServer(builder); Client = _server.CreateClient(); }
/// <summary> /// Authorization /// </summary> /// <param name="code"></param> /// <returns></returns> public ActionResult Authorization(string code) { // Retrieve the authenticator and save it in session for future use var authenticator = GoogleAuthorizationHelper.GetAuthenticator(code); Session["authenticator"] = authenticator; // Save the refresh token locally using (var dbContext = new CalendarContext()) { var userName = User.Identity.Name; var userRegistry = dbContext.GoogleRefreshTokens.FirstOrDefault(c => c.UserName == userName); if (userRegistry == null) { dbContext.GoogleRefreshTokens.Add( new GoogleRefreshToken { UserName = userName, RefreshToken = authenticator.RefreshToken }); } else { userRegistry.RefreshToken = authenticator.RefreshToken; } dbContext.SaveChanges(); } return(RedirectToAction("Index", "Home")); }
public ActionResult Edit(Calendar calendar) { CalendarContext calendarContext = new CalendarContext(); calendarContext.Entry(calendar).State = System.Data.Entity.EntityState.Modified; calendarContext.SaveChanges(); return(RedirectToAction("Admin")); }
public static void DeleteEvent(Event eventToDelete) { using (var db = new CalendarContext()) { var currentEvent = db.Events.FirstOrDefault(e => e.Id == eventToDelete.Id); db.Events.Remove(currentEvent); db.SaveChanges(); } }
public IActionResult Create([Bind] Food newFood, [FromForm] string[] FoodWeightIds, string[] FoodWeightValues) { if (ModelState.IsValid) { CalendarDb.Foods.Add(newFood); CalendarDb.SaveChanges(); // add foodweighttypes // always gram var gramWeighttype = this.CalendarDb.WeightTypes.Where(wt => wt.UnitName == "gram").First(); var fwt = new FoodWeightType() { Food = newFood, FoodId = newFood.FoodID, WeightType = gramWeighttype, WeightTypeId = gramWeighttype.WTID, Weight = Decimal.ToInt32(newFood.Weight) }; for (int i = 0; i < FoodWeightIds.Length; i++) { var weight = FoodWeightValues[i]; var id = FoodWeightIds[i]; if (!string.IsNullOrEmpty(weight)) { var weighttype = this.CalendarDb.WeightTypes.Where(wt => wt.WTID == int.Parse(id)).First(); fwt = new FoodWeightType() { Food = newFood, FoodId = newFood.FoodID, WeightType = weighttype, WeightTypeId = weighttype.WTID, Weight = int.Parse(weight) }; CalendarDb.FoodWeightTypes.Add(fwt); } } CalendarDb.SaveChanges(); return(RedirectToAction("Index")); } ViewBag.WeightTypes = this.CalendarDb.WeightTypes; return(View(newFood)); }
public ContentResult Save(int?id, FormCollection actionValues) { var action = new DataAction(actionValues); var changedEvent = DHXEventsHelper.Bind <schedulerEvent>(actionValues); var entities = new CalendarContext(); var service = getService(); try { switch (action.Type) { case DataActionTypes.Insert: //System.Diagnostics.Debug.WriteLine(changedEvent.text); Event ge = service.Events.Insert(transformEvent(changedEvent), "primary").Execute(); changedEvent.user = User.Identity.GetUserName(); changedEvent.gid = ge.Id; entities.Events.Add(changedEvent); break; case DataActionTypes.Delete: // System.Diagnostics.Debug.WriteLine(changedEvent.gid); service.Events.Delete("primary", changedEvent.gid).Execute(); changedEvent = entities.Events.FirstOrDefault(ev => ev.gid.Equals(changedEvent.gid)); entities.Events.Remove(changedEvent); break; default: // "update" System.Diagnostics.Debug.WriteLine(changedEvent.gid); var target = entities.Events.Single(e => e.gid.Equals(changedEvent.gid)); DHXEventsHelper.Update(target, changedEvent, new List <string> { "id" }); target = entities.Events.Single(e => e.gid.Equals(changedEvent.gid)); var toUpdate = service.Events.Get("primary", target.gid).Execute(); toUpdate.Summary = target.text; toUpdate.Start = new Google.Apis.Calendar.v3.Data.EventDateTime { DateTime = target.start_date.ToUniversalTime() }; toUpdate.End = new Google.Apis.Calendar.v3.Data.EventDateTime { DateTime = target.end_date.ToUniversalTime() }; service.Events.Update(toUpdate, "primary", toUpdate.Id).Execute(); break; } entities.SaveChanges(); action.TargetId = changedEvent.id; } catch (Exception) { action.Type = DataActionTypes.Error; } return(new AjaxSaveResponse(action)); }
public static Event AddEvent(Event newEvent) { using (var db = new CalendarContext()) { var book = db.Events.Add(newEvent); db.SaveChanges(); return(book); } }
public ActionResult DeleteConfirmed(int Id) { CalendarContext calendarContext = new CalendarContext(); Calendar calendar = calendarContext.Calendars.Single(log => log.Id == Id); calendarContext.Calendars.Remove(calendar); calendarContext.SaveChanges(); return(RedirectToAction("Admin")); }
public ActionResult Create(Calendar calendar) { if (ModelState.IsValid) { CalendarContext calendarContext = new CalendarContext(); calendarContext.Calendars.Add(calendar); calendarContext.SaveChanges(); return(RedirectToAction("Admin")); } return(View(calendar)); }
// //Кнопка, добавляет дело в бд. // private void Add_Button_Click(object sender, EventArgs e) { var cases = new ListofCases(); var addCasesForm = new AddCasesForm(); DialogResult result = addCasesForm.ShowDialog(this); if (result == DialogResult.OK) { try { cases.NameEvent = addCasesForm.NameEvent_TextBox.Text; cases.PlaceEvent = addCasesForm.PlaceEvent_TextBox.Text; db.DBListofCases.Add(cases); db.SaveChanges(); dataGridView1.Refresh(); MessageBox.Show("Новое дело добавлено!", "Оповещение", MessageBoxButtons.OK, MessageBoxIcon.Asterisk); } catch (Exception ex) { MessageBox.Show(ex.Message, ex.Source, MessageBoxButtons.OK, MessageBoxIcon.Error); } } }
public void InitializeDB() { _calendarContext.Database.EnsureCreated(); if (_calendarContext.calendarEntries.Any()) { return; } _calendarContext.AddRange(CreateList()); _calendarContext.SaveChanges(); }
public static Event UpdateEvent(Event newEvent) { using (var db = new CalendarContext()) { var currentEvent = db.Events.FirstOrDefault(e => e.Id == newEvent.Id); currentEvent.Name = newEvent.Name; currentEvent.StartDate = newEvent.StartDate; currentEvent.EndDate = newEvent.EndDate; db.SaveChanges(); return(currentEvent); } }
/// <summary> /// Helper method for creating inMemoryDb /// </summary> /// <param name="items">database items </param> /// <param name="dbName"> if not provided it will generate a ranom database-name </param> public static CalendarContext CreateInMemoryDB(List <CalendarEntrie> items, string dbName = null) { dbName = (dbName != null ? dbName : Guid.NewGuid().ToString()); var options = new DbContextOptionsBuilder <CalendarContext>() .UseInMemoryDatabase(databaseName: dbName) .Options; var context = new CalendarContext(options); items.ForEach(n => context.calendarEntries.Add(n)); context.SaveChanges(); return(context); }
public void TestUpsert() { using (var context = new CalendarContext("Data Source=localhost;Initial Catalog=StaffCalendars;Integrated Security=True")) { var cons = context.Rosters.FirstOrDefault(); if (cons == null) { cons = new ServerRoster { Id = Guid.Parse("D43880FF-6368-442D-85D6-01BB5CC6523C"), DepartmentName = "SS PICU", RosterName = "Consultants", Secret = HexadecimalStringToByteArray_Original("2CBC90D518D6066F579EC5E85F77C366D63FEF1616A4DD9D6646ED42BFC16C694B53221DB55627305213B3280F591EEB171610EE7013C20F76AB5057EA36A59E") //Convert.FromBase64String("hJ4blpw8qTI5PEFpdzM2cNpnf6qTNzSBys+x8zQjjojcrVLvPPrXbmpg1ICXgYAg7AprMxz5EiOId9qOR8avzw==") // 0x2CBC90D518D6066F579EC5E85F77C366D63FEF1616A4DD9D6646ED42BFC16C694B53221DB55627305213B3280F591EEB171610EE7013C20F76AB5057EA36A59E }; context.Rosters.Add(cons); context.SaveChanges(); } context.Upsert(new[] { new ServerStaffMember { /*Id = Guid.Parse("632036E2-C3CF-4116-B9B9-59AB075AB0DA"), */ FullName = "Alex Hussey", Roster = cons, StaffMemberCode = "AH" }, new ServerStaffMember { /*Id = Guid.Parse("1B435B77-0062-411F-9B6B-1B3C154D2E6D"), */ FullName = "Anusha Ganeshalingham", Roster = cons, StaffMemberCode = "AG" }, new ServerStaffMember { /*Id = Guid.Parse("BFE2AE9C-2C9A-4730-8D20-4BBC370461AB"), */ FullName = "Brent McSharry", Roster = cons, StaffMemberCode = "BM" }, new ServerStaffMember { /*Id = Guid.Parse("A1F39FFD-1161-4474-8823-8BB441395A2A"), */ FullName = "Fiona Miles", Roster = cons, StaffMemberCode = "M" }, new ServerStaffMember { /*Id = Guid.Parse("F4DE1C5A-AA18-4A99-B300-6183000CDC93"), */ FullName = "Gabrielle Nuthall", Roster = cons, StaffMemberCode = "N" }, new ServerStaffMember { /*Id = Guid.NewGuid(),*/ FullName = "Dave Buckley", Roster = cons, StaffMemberCode = "BU" }, new ServerStaffMember { /*Id = Guid.NewGuid(),*/ FullName = "John Beca", Roster = cons, StaffMemberCode = "BE" }, new ServerStaffMember { /*Id = Guid.NewGuid(),*/ FullName = "Brian Anderson", Roster = cons, StaffMemberCode = "A" }, new ServerStaffMember { /*Id = Guid.NewGuid(),*/ FullName = "Liz Segedin", Roster = cons, StaffMemberCode = "S" } }); } }
public ActionResult DeleteCalendarEvent(string id) { int eventID = Convert.ToInt32(id); using (CalendarContext db = new CalendarContext()) { // Delete CalendarEvent from database CalendarEvent calEventToDelete = db.CalendarEvents.Where(ce => ce.EventID == eventID).FirstOrDefault(); db.CalendarEvents.Remove(calEventToDelete); db.SaveChanges(); } return(View()); }
public ActionResult UploadCalendarEvent(HttpPostedFileBase uploadFile) { int newID = 0; if (uploadFile == null) { return(RedirectToLocal("/Calendar/Index")); } StreamReader csvreader = new StreamReader(uploadFile.InputStream); while (!csvreader.EndOfStream) { var line = csvreader.ReadLine(); var values = line.Split(','); try { // Create new CalendarEvent to pass to database CalendarEvent calEvent = new CalendarEvent { FBID = (String)Session["FBID"], Title = values[0], Description = values[1], Location = values[2], StartTime = Convert.ToDateTime(values[3]), EndTime = Convert.ToDateTime(values[4]), Recurring = Boolean.Parse(values[5]), AllDay = Boolean.Parse(values[6]) }; using (CalendarContext db = new CalendarContext()) { db.CalendarEvents.Add(calEvent); db.SaveChanges(); newID = calEvent.EventID; } } catch (Exception e) // If we can't read the file or it is in the wrong format { return(RedirectToLocal("/Calendar/Index")); } } // Return the new ID value so we can set it on the new calendar object //return Json(newID, JsonRequestBehavior.AllowGet); return(RedirectToLocal("/Calendar/Index")); }
public ActionResult UpdateCalendarEvent(string id, string title, string description, string location, string start, string end, string allDay) { // Convert start and end to DateTime objects /* * DateTime startTime = DateTime.ParseExact(start, "dd-MM-yyyy HH:mm:ss", * System.Globalization.CultureInfo.InvariantCulture); * DateTime endTime = DateTime.ParseExact(end, "dd-MM-yyyy HH:mm:ss", * System.Globalization.CultureInfo.InvariantCulture); */ int eventID = Convert.ToInt32(id); using (CalendarContext db = new CalendarContext()) { // Update CalendarEvent in database CalendarEvent calEventToUpdate = db.CalendarEvents.Where(ce => ce.EventID == eventID).FirstOrDefault(); // Create CalendarEvent to be passed to database // Only title, description, and location can be updated currently CalendarEvent calEvent = new CalendarEvent { EventID = Convert.ToInt32(id), FBID = (String)Session["FBID"], Title = title, Description = description, Location = location, StartTime = calEventToUpdate.StartTime, EndTime = calEventToUpdate.EndTime, Recurring = false, AllDay = calEventToUpdate.AllDay }; if (calEventToUpdate != null) { db.Entry(calEventToUpdate).CurrentValues.SetValues(calEvent); } db.SaveChanges(); } return(View()); }
public void AddRecord([FromBody] Entities.Shedule shedule, String date) { context.Database.EnsureCreated(); var dbShedule = context.Shedules.Where(s => s.Date == shedule.date).ToList(); if (dbShedule.Count == 0) { context.Shedules.Add(Logic.Entity2DBEntityParser.parseShedule(shedule)); } else { var tasksToRemove = context.Tasks.Where(s => s.SheduleId == dbShedule[0].Id).ToList(); context.Tasks.RemoveRange(tasksToRemove); List <Entities.Task> eTasks = shedule.tasksList; List <Database.Entities.Task> tasksList = new List <Task>(); foreach (Entities.Task task in eTasks) { tasksList.Add(Entity2DBEntityParser.parseTask(task)); } dbShedule[0].TasksList = tasksList; context.Shedules.Update(dbShedule[0]); } context.SaveChanges(); }
public ContentResult Save(int?id, FormCollection actionValues) { var action = new DataAction(actionValues); var changedEvent = DHXEventsHelper.Bind <Event>(actionValues); var entities = new CalendarContext(); try { switch (action.Type) { case DataActionTypes.Insert: entities.Events.Add(changedEvent); break; case DataActionTypes.Delete: changedEvent = entities.Events.FirstOrDefault(ev => ev.id == action.SourceId); entities.Events.Remove(changedEvent); break; default: // "update" var target = entities.Events.Single(e => e.id == changedEvent.id); DHXEventsHelper.Update(target, changedEvent, new List <string> { "id" }); break; } entities.SaveChanges(); action.TargetId = changedEvent.id; } catch (Exception a) { action.Type = DataActionTypes.Error; } return(new AjaxSaveResponse(action)); }
public void Update() { using (var context = new CalendarContext(_credentials)) { // add the calendar var calendar = context.Calendars.Where(w => w.ID == this.CalendarID).First(); calendar.AuthorID = _credentials.UserID; calendar.Description = this.Description; calendar.Name = this.Name; // update the invitees // check id's to update? // add the history record var history = new CalendarHistory(); history.CalendarID = this.CalendarID; history.TransactionDate = DateTime.Now; history.TransactionType = Data.Enumeration.CalendarHistoryType.Edit; history.UserID = _credentials.UserID; context.CalendarHistory.Add(history); context.SaveChanges(); } }
public void Insert() { using (var context = new CalendarContext(_credentials)) { // add the calendar var calendar = new Data.Tables.Calendar(); calendar.AuthorID = _credentials.UserID; calendar.Description = this.Description; calendar.Name = this.Name; context.Calendars.Add(calendar); context.SaveChanges(); this.CalendarID = calendar.ID; // Sharing foreach (var invitee in _calendarInvitees) { invitee.CalendarID = this.CalendarID; context.CalendarInvitees.Add(invitee); } // add the history record var history = new CalendarHistory(); history.CalendarID = this.CalendarID; history.TransactionDate = DateTime.Now; history.TransactionType = Data.Enumeration.CalendarHistoryType.Create; history.UserID = _credentials.UserID; context.CalendarHistory.Add(history); context.SaveChanges(); } }