Question: Entity Framework 7 IDENTITY_INSERT


Entity Framework 7 IDENTITY_INSERT

Answers 1
Added at 2016-01-11 20:01

I need to store a large amount of user data in database in which every user already has an ID as a key. However, these users all out of a larger pool of users, therefore, the ID does not increment and cannot be automatically generated. I need to be able to manually set the ID.

Is there an easy way to do this?

nr: #1 dodano: 2016-01-11 20:01

I've made some tests and this seems to work for me on EF 7.0.0 rc1-final:

modelBuilder.Entity<Foo>().HasKey(x => x.Id);
modelBuilder.Entity<Foo>().Property(x => x.Id).ValueGeneratedNever();    

My test code:

static void Main(string[] args)
    using (var db = new FooContext())
        var myFoo = new Foo {Id = 1002, Descr = "Test"};
    using (var db = new FooContext())
        var myFoo = db.Foos.FirstOrDefault(x => x.Id == 1002);
        Console.WriteLine($"id = {myFoo?.Id}, descrip = {myFoo?.Descr}");

(full program code here:

It correctly inserts and retrieves a record with the specified id and the table has the correct primary key specified.

This is the migration code generated:

    name: "Foo",
    columns: table => new
        Id = table.Column<long>(nullable: false),
        Descr = table.Column<string>(nullable: true)
    constraints: table =>
        table.PrimaryKey("PK_Foo", x => x.Id);
Source Show
◀ Wstecz