Entity Framework 7 IDENTITY_INSERT

前端 未结 1 1182
囚心锁ツ
囚心锁ツ 2021-01-22 15:53

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

1条回答
  •  伪装坚强ぢ
    2021-01-22 16:12

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

    modelBuilder.Entity().HasKey(x => x.Id);
    modelBuilder.Entity().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(nullable: false),
            Descr = table.Column(nullable: true)
        },
        constraints: table =>
        {
            table.PrimaryKey("PK_Foo", x => x.Id);
        });
    

    0 讨论(0)
提交回复
热议问题