简体   繁体   中英

How to insert data row using Entity Framework with Auto Increment column

I have a table name Product

It have two columns ProductID (primary key and auto incremented(1,1) and ProductName .

my product Model:

public partial class Product
{
  public int ProductID {get; set;}
  public string ProductName {get; set;}
}

I am trying to insert the row in the database using entity as:

    using(var db = new DbContext()){
    
        Product row = new Product ()
                            {
                             ProductName = "product1"
                            };
                            db.Products.Add(row);
                            db.SaveChanges();
       }

but it store id as 0 and not the auto incremented value decided by SQL Sever

try to add this decorator

public partial class Product
{
  [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
  [Key]
  public int ProductID {get; set;}
  public string ProductName {get; set;}
}

greetings,

Mike

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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