简体   繁体   中英

Create a new record with Entity Framework

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; }

在使用SaveChanges()提交记录之前,不会创建记录。

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.

I think that when a new record is created, id will be incremented by 1.

Who does that? The DBMS. Where does the record currently live? Only in your application.

Call testContext.SaveChanges() to insert the record in the database, after which the entity's id property will be updated.

SaveChanges() returns the number of rows affected. If it returns 0, then nothing has been saved. To check if the item has been saved:

int rows affected = 0;
if(rows_affected = context.SaveChanges() > 0)
   System.Writeline("Saved!");
else
   System.Writeline("Nothing saved! Check error using try catch");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM