title: Generate and auto increment the Id in Entity Framework database first
body: <p>I have a table <code>CampaignLanguage</code>. The primary key is Id. It should be auto increment.
  So I have the code:</p>
  
  <pre><code> public partial class CampaignLanguage
  {
      public CampaignLanguage()
      {
          this.CampaignLanguageQuestions = new HashSet&lt;CampaignLanguageQuestion&gt;();
      }
  
      [Key]
      [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
      public int Id { get; set; }
  </code></pre>
  
  <p>Then in the controller, I want to save the generated object.</p>
  
  <pre><code> [HttpPost]
      public ActionResult Save(int clientId, int campaignId)
      {
          var campaign = CampaignService.GetCampaignById(campaignId);
          var campaignLanguage = campaign.CampaignLanguages.Where(x =&gt; x.CampaignId == campaignId).FirstOrDefault();
          if (campaignLanguage != null)
          {
              campaignLanguage.WelcomeMessage = message;
              CampaignService.Save(campaignLanguage);
          }
          else
          {
              campaignLanguage = new CampaignLanguage();
              campaignLanguage.Id = 1;
  
              CampaignService.Save(campaignLanguage);
          }
          return Redirect("/Campaign/Index/" + clientId);
      }
  </code></pre>
  
  <p>However, I get the error.</p>
  
  <blockquote>
    <p>{"Store update, insert, or delete statement affected an unexpected number of rows (0). Entities may have been modified or deleted since entities were loaded. Refresh ObjectStateManager entries."}</p>
  </blockquote>
  
  <p>I don't want to change my CampaignService.Save method. So how to fix it?</p>
  
  <p><strong>EDIT</strong></p>
  
  <pre><code>    public void Save(CampaignLanguage campaignLanguage)
      {
          _campaignLanguageRepository.Update(campaignLanguage);
          _unitOfWork.Commit();
      }
  </code></pre>
  
  <p><strong>EDIT 1</strong></p>
  
  <pre><code>   public virtual void Add(T entity)
     {
         dbset.Add(entity);           
     }
     public virtual void Update(T entity)
     {
         dbset.Attach(entity);
         dataContext.Entry(entity).State = EntityState.Modified;
     }
  </code></pre>