使用Entity Framework创建新记录

5

我有一张表,其中的主键id是一个自增列。我认为当创建新记录时,id会自动加1。

然而,在调试过程中,我发现id的值为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; }

1
调用SubmitChanges后,该值将被递增。 - 2GDev
1
你是否已经持久化了实体(即,将其附加到上下文并调用 SaveChanges)? - J0HN
你是在调用 DbContextSaveChanges 之前还是之后进行检查? - jeroenh
4个回答

9

只有通过 SaveChanges() 提交记录后,才会创建该记录。


5

它的值为0是因为它尚未创建。

        TestContext context = new TestContext();

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

        context.IncrementTest.Add(increment);


        context.SaveChanges();

对我来说,这个程序可以正常工作而不会抛出任何异常。

1
我认为当创建新记录时,id会自动加1。
谁做到了这一点?数据库管理系统。当前记录在哪里?只存在于您的应用程序中。
调用testContext.SaveChanges()将记录插入数据库,此后实体的id属性将被更新。

0

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");

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接