实体框架7 IDENTITY_INSERT
我需要大量的用户数据的存储在每个用户已经拥有的ID作为密钥的数据库。但是,这些用户都出用户的一个较大的池,因此,该ID不增加,并且不能自动生成。我需要能够手动设置的ID。
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?
我做了一些测试,这似乎为我工作的EF 7.0.0 RC1决赛:
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}");
}
}
(完整的程序代码在这里:的 http://pastebin.com/hSs9HZCP )
它正确地插入和检索与指定的id和表中的记录有指定了正确的主键
It correctly inserts and retrieves a record with the specified id and the table has the correct primary key specified.
这是生成的迁移代码:
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);
});