How EF generate insertion SQL for entity class that has default 0?

asp.net-core asp.net-mvc c# entity-framework-core sql-server

Question

I'm new to Entity Framework, just a question on how EF generate insertion SQL for entity class that has default 0.

This is the data model class:

public class Product
{
    public long ProductID { get; set; }
    public string Name { get; set; }
}

and the underlying table Products in Sql server has identity column on ProductID .

So let's say a controller that use model binding to create a Product object p1, and then we do:

context.Products.Add(p1)   //p1.ProductID = 0 for default
context.SaveChanges();

My questions are:

  1. Does EF need to send a query to database to get latest primary key in Products table and then plus 1 to be p1.ProductID? Isn't that very inefficient as you need to query database for latest existing primary key and then send another insert SQL to insert record?

  2. what does the Dbset<Product>.add() method really mean? I mean if the object's id is 0, we know it doesn't exist in the database (if id > 0 then we know we are modifying existing record), can't we just add newly created p1 to the database, why we still need to track it?

1
0
7/23/2019 4:29:01 AM

Popular Answer

1.) no, you dont need to get latest object's primary key to determine next Id.

2.) Primary Key starts from 1 not 0,in EF if you use default identity provider as explained below, EF can manage Primary Key auto, so no need to set ANY number to that variable. Then, context.Products.Add(p1) adds value to Local Table (in RAM), after addition context.SaveChanges(); will trigger to send Local Values to SQL Database.After SaveChanges you will see correct Id of value

there is a feature to generate auto Id for tables.

  • firstly, you should select which property is Primary Key with [Key] attribute.
  • Secondly, you should determine the type of Primary Key whether Integer or String (string has no auto Id Generator)
  • Then, if it is Integer and you need auto Id generator, you should use [DatabaseGenerated(DatabaseGeneratedOption.Identity)] to auto generator.
  • After that, you dont worry about value of ProductID EF can manage it.
public class Product
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public long ProductID { get; set; }
    public string Name { get; set; }
}

not: if you want string Primary Key (or manually add Id) you should use [DatabaseGenerated(DatabaseGeneratedOption.None)]

more examples about EF (select EF version from navigator)

1
7/23/2019 4:22:19 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow