Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Code-First Entity Framework inserting data with custom ID

I am using code-first EF in my project and face issue when the data with custom id is being inserted.

When I am trying to insert data with custom ID (for instance 999), EF ignores it and inserts incremented ID into table.

My model:

public class Address
{
        [Key]
        public int Id { get; set; }
        public string FirstName { get; set; }
...
}

How to solve this probleb?

EDIT:

1) How to begin incrementing from N, but not from 0?

2) If I don't specify custom ID, DB must increment and inserts own. If I specify custom ID, DB must insert it. Is it possible?

like image 609
Serhii Kyslyi Avatar asked Oct 04 '12 13:10

Serhii Kyslyi


1 Answers

you can use the following attribute

[Key, DatabaseGenerated(DatabaseGeneratedOption.None)]

on the key to your class or using fluentAPI

modelBuilder.Entity<Address>().Property(p => p.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
like image 141
JTMon Avatar answered Sep 29 '22 12:09

JTMon