简体   繁体   English

使用Entity Framework创建新记录

[英]Create a new record with Entity Framework

I have a table whose primary key id is an identity column. 我有一个表,其主键id是一个标识列。 I think that when a new record is created, id will be incremented by 1. 我认为在创建新记录时,id将增加1。

However I found that it is 0 while debugging. 但是我发现在调试时它是0。 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. 它是0,因为它尚未创建。

        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. 我认为在创建新记录时,id将增加1。

Who does that? 谁那样做? The DBMS. 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. 调用testContext.SaveChanges()将记录插入数据库,之后将更新实体的id属性。

SaveChanges() returns the number of rows affected. SaveChanges()返回受影响的行数。 If it returns 0, then nothing has been saved. 如果返回0,则表示没有保存任何内容。 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");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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