title: Entity Framework - How to add db entries without a form
body: <p>Usually I add new database entries with a &quot;Create&quot; form, just like the template you are given like this:</p>
  <pre><code>[HttpPost]
  [ValidateAntiForgeryToken]
  public ActionResult Create([Bind(Include = &quot;MyObjectProperties&quot;)] MyObject MyObjectName)
  {
      if (ModelState.IsValid)
      {
          db.MyObjects.Add(MyObjectName);
          db.SaveChanges();
          return RedirectToAction(&quot;Index&quot;);
      }
  
      return View(MyObjectName);
  }
  </code></pre>
  <p>Which works just fine. However, I'm trying to delete all entries in my database and then add them again one by one. The purpose is that the table is filled with deadline dates for each week in a year, and this method will reset the deadlines and set the correct dates for the given year. This is the method that performs that task:</p>
  <pre><code>public bool ResetDeadlines()
  {
      //db.Canteen_Deadlines.RemoveRange(db.Canteen_Deadlines);
  
      int monthOfLastWeek = 1;
      DateTime deadlineDate;
      int weekOfMonth = 0;
      int year = DateTime.Now.Year;
  
      for (var i = 1; i &lt; 53; i++)
      {
          if (i == 1)
              year += 1;
          else
              year = DateTime.Now.Year;
  
          deadlineDate = GetThursdayOfWeek(year, i).AddDays(-7); //Gets the thursday of the week before, because that is the deadline for that week.
          weekOfMonth = monthOfLastWeek &lt; deadlineDate.Month ? 1 : weekOfMonth + 1;
  
          var newDeadline = new Canteen_Deadlines
          {
              N = DaysFromNewYear(year, deadlineDate),
              DeadlineDate = deadlineDate,
              WeekNo = (byte)i,
              MonthNo = (byte)deadlineDate.Month,
              QuarterNo = (byte)GetQuarterNumber(deadlineDate.Month),
              YearNo = (short)year,
              DayofWeek = 4,
              LastDowInMonth = IsLastDoWInMonth(deadlineDate),
              DoWAsc = (byte)weekOfMonth
          };
  
          db.Canteen_Deadlines.Add(newDeadline);
          //db.Entry(newDeadline).State = EntityState.Added;
          db.SaveChanges();
  
          monthOfLastWeek = deadlineDate.Month;
      }
  
      return true;
  }
  </code></pre>
  <p>The problem arises when I do <code>db.SaveChanges();</code>. It will give me a <code>DbUpdateConcurrencyException</code>, saying that none of the rows in the database has been affected. I can't seem to figure out the difference between my method and the template create method. Other posts online are more focused on this problem arising when using the template create method and people not using &quot;Html.HiddenFor&quot; on their ID. This is not a viable solution for me, since I am not using a form and therefore have no way of using the Html helper. The user will just press a &quot;Reset deadlines&quot; button.</p>
  <p>The &quot;N&quot; property on the objects are their keys. It is the amount of days the given date is into the year, meaning 16th of January would be N = 16. As the deadlines only are for 1 year, the N values will not conflict and therefore should be able to be used as keys.</p>
  <p>How can I save these entries in the database successfully? I have commented out the db.remove method, just to get the adding of entries to work. I have also tried setting the entry states to added, but that did not work either. I tried debugging and confirmed that all properties of the object is initialized correctly.</p>
  <p>Full exception:</p>
  <pre><code>[OptimisticConcurrencyException: Store update, insert, or delete statement affected an unexpected number of rows (0). Entities may have been modified or deleted since entities were loaded. See http://go.microsoft.com/fwlink/?LinkId=472540 for information on understanding and handling optimistic concurrency exceptions.]
     System.Data.Entity.Core.Mapping.Update.Internal.UpdateTranslator.ValidateRowsAffected(Int64 rowsAffected, UpdateCommand source) +142
     System.Data.Entity.Core.Mapping.Update.Internal.UpdateTranslator.Update() +525
     System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransaction(Func`1 func, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction, Boolean releaseConnectionOnSuccess) +453
     System.Data.Entity.Core.Objects.ObjectContext.SaveChangesToStore(SaveOptions options, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction) +252
     System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute(Func`1 operation) +206
     System.Data.Entity.Core.Objects.ObjectContext.SaveChangesInternal(SaveOptions options, Boolean executeInExistingTransaction) +270
     System.Data.Entity.Internal.InternalContext.SaveChanges() +145
  
  [DbUpdateConcurrencyException: Store update, insert, or delete statement affected an unexpected number of rows (0). Entities may have been modified or deleted since entities were loaded. See http://go.microsoft.com/fwlink/?LinkId=472540 for information on understanding and handling optimistic concurrency exceptions.]
     System.Data.Entity.Internal.InternalContext.SaveChanges() +280
     MyProject.Models.Services.DeadlinesService.ResetDeadlines() in \\PROJECTPATH\Models\Services\DeadlinesService.cs:49
     MyProject.Controllers.AdminController.ResetDeadlines() in \\PROJECTPATH\Controllers\AdminController.cs:254
     lambda_method(Closure , ControllerBase , Object[] ) +87
     System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +35
     System.Web.Mvc.Async.&lt;&gt;c.&lt;BeginInvokeSynchronousActionMethod&gt;b__9_0(IAsyncResult asyncResult, ActionInvocation innerInvokeState) +39
     System.Web.Mvc.Async.WrappedAsyncResult`2.CallEndDelegate(IAsyncResult asyncResult) +77
     System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult) +42
     System.Web.Mvc.Async.&lt;&gt;c__DisplayClass11_0.&lt;InvokeActionMethodFilterAsynchronouslyRecursive&gt;b__0() +80
     System.Web.Mvc.Async.&lt;&gt;c__DisplayClass11_2.&lt;InvokeActionMethodFilterAsynchronouslyRecursive&gt;b__2() +387
     System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethodWithFilters(IAsyncResult asyncResult) +42
     System.Web.Mvc.Async.&lt;&gt;c__DisplayClass3_6.&lt;BeginInvokeAction&gt;b__4() +50
     System.Web.Mvc.Async.&lt;&gt;c__DisplayClass3_1.&lt;BeginInvokeAction&gt;b__1(IAsyncResult asyncResult) +188
     System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +38
     System.Web.Mvc.&lt;&gt;c.&lt;BeginExecuteCore&gt;b__152_1(IAsyncResult asyncResult, ExecuteCoreState innerState) +26
     System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +73
     System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +52
     System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +39
     System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +38
     System.Web.Mvc.&lt;&gt;c.&lt;BeginProcessRequest&gt;b__20_1(IAsyncResult asyncResult, ProcessRequestState innerState) +40
     System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +73
     System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +38
     System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +602
     System.Web.HttpApplication.ExecuteStepImpl(IExecutionStep step) +195
     System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean&amp; completedSynchronously) +128
  
  </code></pre>
  <p>EDIT:
  Controller Action:</p>
  <pre><code>public ActionResult ResetDeadlines()
          {
              deadlinesService.ResetDeadlines();
  
              return RedirectToAction(&quot;IndexDeadlines&quot;);
          }
  </code></pre>
  <p>View:</p>
  <pre><code>@using (Html.BeginForm())
  {
      @Html.AntiForgeryToken()
  
      &lt;div class=&quot;form-horizontal&quot;&gt;
          &lt;div class=&quot;row&quot; style=&quot;margin-left:0px&quot;&gt;
              &lt;div&gt;
                  &lt;label for=&quot;SearchInput&quot; style=&quot;font-size:18px&quot;&gt;@Res.Search @Res.Week&lt;/label&gt;
                  @Html.Editor(&quot;Search&quot;, new { htmlAttributes = new { @class = &quot;form-control&quot;, @autofocus = &quot;autofocus&quot;, @id = &quot;SearchInput&quot;, @onkeyup = &quot;myFunction()&quot; } })
              &lt;/div&gt;
              &lt;div style=&quot;margin-left:10px;margin-top:18px&quot;&gt;
                  &lt;a href=&quot;@Url.Action(&quot;ResetDeadlines&quot;)&quot; class=&quot;customBtnXSmall&quot;&gt;Reset Deadlines&lt;/a&gt;
              &lt;/div&gt;
          &lt;/div&gt;
      &lt;/div&gt;
  }
  </code></pre>
  <p>This is the Deadline class:</p>
  <pre><code>using System;
  using System.Collections.Generic;
  using System.ComponentModel.DataAnnotations;
  using System.ComponentModel.DataAnnotations.Schema;
  using System.Linq;
  using System.Web;
  
  namespace MyProject.Models.DBModels
  {
      public class Canteen_Deadlines
      {
          [Key]
          public long? N { get; set; } //Number of days into the year (16th of January is 16 days into the year, so N would be = 16)
          [Column(TypeName = &quot;smalldatetime&quot;)]
          public DateTime? DeadlineDate { get; set; }
          public byte? WeekNo { get; set; }
          public byte? MonthNo { get; set; }
          public byte? QuarterNo { get; set; }
          public short YearNo { get; set; }
          public byte? DayofWeek { get; set; }
          public bool? LastDowInMonth { get; set; } //Last DayOfWeek In Month
          public byte? DoWAsc { get; set; } //DayOfWeek Ascending
      }
  }
  </code></pre>