title: How to deal with identity columns while insertion in MVC
body: <p>I am learning MVC &amp; have a demo MVC application, where I am trying to save UserId, Name &amp; Email.</p>
  
  <p>UserId is int primary key &amp; identity as well.</p>
  
  <p>In my create view page I have fields for Name &amp; Email only. But on post It's taking default value of int(0) for UserId as well and hence I am getting following exception.</p>
  
  <pre><code>Cannot insert explicit value for identity column in table 'Users' when IDENTITY_INSERT is set to OFF.
  </code></pre>
  
  <p>Here is my Model class:</p>
  
  <pre><code> namespace LearningMvc.Models
   {
   public class Users
   {
      [Key]
      [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
      public int UserId { get; set; }
  
      [Required(ErrorMessage = "Please enter your name")]
      public string Name { get; set; }
  
      [Required(ErrorMessage = "Please enter your email address")]
      [RegularExpression(".+\\@.+\\..+",
      ErrorMessage = "Please enter a valid email address")]
      public string Email { get; set; }
  }
  }
  </code></pre>
  
  <p>Here's my action method:</p>
  
  <pre><code>    [HttpPost]
      public ActionResult Create([Bind(Exclude = "UserId")] Users NewUser)
      {
          try
          {
              var ObjDbContext = new MyDbDataContext();
              ObjDbContext.Users.InsertOnSubmit(NewUser);
              ObjDbContext.SubmitChanges();
              return RedirectToAction("Index");
          }
          catch (Exception Ex)
          {
              throw Ex;
          }
      }
  </code></pre>
  
  <p>Connection string in config</p>
  
  <pre><code> &lt;connectionStrings&gt;
  &lt;add name="DemoDbForMvcConnectionString" connectionString="Data Source=RASHMITAD7;Initial Catalog=DemoDbForMvc;Integrated Security=True"
    providerName="System.Data.SqlClient" /&gt;
  </code></pre>
  
  <p></p>
  
  <p>Here's dbml file:</p>
  
  <pre><code>       &lt;?xml version="1.0" encoding="utf-8"?&gt;&lt;Database Name="DemoDbForMvc" Class="MyDbDataContext" xmlns="http://schemas.microsoft.com/linqtosql/dbml/2007"&gt;
      &lt;Connection Mode="WebSettings" ConnectionString="Data Source=RASHMITAD7;Initial Catalog=DemoDbForMvc;Integrated Security=True" SettingsObjectName="System.Configuration.ConfigurationManager.ConnectionStrings" SettingsPropertyName="DemoDbForMvcConnectionString" Provider="System.Data.SqlClient" /&gt;
      &lt;Table Name="dbo.[Users]" Member="Users"&gt;
        &lt;Type Name="Users"&gt;
          &lt;Column Name="UserId" Type="System.Int32" DbType="Int NOT NULL" IsPrimaryKey="true" CanBeNull="false"/&gt;
          &lt;Column Name="Name" Type="System.String" DbType="NVarChar(100)" CanBeNull="true" /&gt;
          &lt;Column Name="Email" Type="System.String" DbType="NVarChar(50)" CanBeNull="true" /&gt;
        &lt;/Type&gt;
      &lt;/Table&gt;
    &lt;/Database&gt;
  </code></pre>