簡體   English   中英

使用Entity Framework創建新記錄

[英]Create a new record with Entity Framework

我有一個表,其主鍵id是一個標識列。 我認為在創建新記錄時,id將增加1。

但是我發現在調試時它是0。 為什么?

必要的代碼:

  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()提交記錄之前,不會創建記錄。

它是0,因為它尚未創建。

        TestContext context = new TestContext();

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

        context.IncrementTest.Add(increment);


        context.SaveChanges();

這對我來說沒有任何例外。

我認為在創建新記錄時,id將增加1。

誰那樣做? DBMS。 記錄目前在哪里? 僅在您的申請中。

調用testContext.SaveChanges()將記錄插入數據庫,之后將更新實體的id屬性。

SaveChanges()返回受影響的行數。 如果返回0,則表示沒有保存任何內容。 要檢查項目是否已保存:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM