实体框架7 IDENTITY_INSERT [英] Entity Framework 7 IDENTITY_INSERT

查看:243
本文介绍了实体框架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);
    });

这篇关于实体框架7 IDENTITY_INSERT的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆