繁体   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