title: c# creating DB from code
body: <p>My program keeps crashing when I am trying to add from code Person details,name in this example</p>
  
  <p>Take a look at my code</p>
  
  <pre><code>using System;
  using System.Collections.Generic;
  using System.Linq;
  using System.Text;
  using System.Threading.Tasks;
  using System.Data.Entity;
  
  namespace ConsoleApplication4
  {
      class Program
      {
          static void Main(string[] args)
          {
              using (var db = new PersonContext())
              {
                  // Create and save a new Person 
                  Console.Write("Enter a name for a new Person Name: ");
                  var name = Console.ReadLine();
                  //Adding new person to the DB
                  var person = new Person { Name = name };
                  db.Persons.Add(person);
                  db.SaveChanges();
  
                  // Display all Blogs from the database 
                  var query = from p in db.Persons
                              orderby p.Name
                              select p;
  
                  Console.WriteLine("All persons in the database:");
                  foreach (var item in query)
                  {
                      Console.WriteLine(item.Name);
                  }
  
                  Console.WriteLine("Press any key to exit...");
                  Console.ReadKey();
              }
  
          }
      }
  
      public class Person
      {
          public int NameId { get; set; }
          public string Name { get; set; }
          public virtual List&lt;Person&gt; Persons { get; set; }
  
      }
  
  
  
      public class PersonContext : DbContext
      {
          public DbSet&lt;Person&gt; Persons { get; set; }
      }
  }
  </code></pre>
  
  <p>When it reach this line:</p>
  
  <pre><code>            db.Persons.Add(person);
  </code></pre>
  
  <p>it crash, complaining that the person does not have an id, but even if I give it direct ID number it does not help me resolve the issue.
  Looking at the debug I see it gets ID 0 so I am not sure this is actually the problem.
  I took the sample code from here <a href="https://msdn.microsoft.com/en-us/data/jj193542" rel="nofollow">https://msdn.microsoft.com/en-us/data/jj193542</a></p>
  
  <p>And customize it to my own needs.
  Any idea?</p>