Entity Framework 7 IDENTITY_INSERT

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

Question

I need to store a large amount of user data in a database where 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?

Accepted Answer

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"};
        db.Add(myFoo);
        db.SaveChanges();
    }
    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: http://pastebin.com/hSs9HZCP)

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:

migrationBuilder.CreateTable(
    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);
    });


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