Create a new record with Entity Framework

c# entity-framework sql-server

Question

I have a table whose primary key id is an identity column. I think that when a new record is created, id will be incremented by 1.

However I found that it is 0 while debugging. Why?

The necessary code:

  public DbSet<testDetails> testDetailRecords { get; set; }
  testDetails test = testContext.testDetailRecords.Create();
  // test.id is 0 when hover over it
  public class testDetails : IEntityWithRelationships
  {
      [Key]
       [Required]
       [Display(Name = "Primary Key", Description = "Primary Key")]
       [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
       public long id { get; set; }
1
4
11/15/2012 3:56:53 PM

Accepted Answer

The record is not created until you commit it with a SaveChanges().

9
11/15/2012 3:59:09 PM

Popular Answer

It is 0 because it is not created yet.

        TestContext context = new TestContext();

        var increment = context.IncrementTest.Create();
        increment.name = "testbyme";

        context.IncrementTest.Add(increment);


        context.SaveChanges();

That works without throwing any exceptions for me.



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow