使用实体框架创建新记录

问题描述 投票:0回答:4

我有一个表,其主键 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; }
c# sql-server entity-framework
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 rowsAffected = context.SaveChanges();
if (rowsAffected > 0)
   Console.WriteLine("Saved!");
else
   Console.WriteLine("Nothing saved! Check error using try catch");
© www.soinside.com 2019 - 2024. All rights reserved.