如何在.net核心中打开身份插入 [英] How to turn on identity-insert in .net core

查看:74
本文介绍了如何在.net核心中打开身份插入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在EF中创建了一些表,并输入了一些种子数据,在其中使用主键为几列赋值。当我运行应用程序时,我收到错误消息:

I made a few tables in EF and entered in some seed data where I give value to a few columns with a primary key. When I run the application I am getting the error message:

当IDENTITY_INSERT设置为OFF时,无法为表'Persons'中的Identity列插入显式值。

Cannot insert explicit value for identity column in table 'Persons' when IDENTITY_INSERT is set to OFF.

如何打开它?我在这里阅读使用:

How do I turn it on? I read on here to use:

[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]

在作为主键的属性上方。不幸的是,我仍然收到相同的错误消息。请帮忙。

above the property that is a primary key. I am still getting the same error message unfortunately. Please help.

我向所有具有主键的属性添加了 [DatabaseGenerated(DatabaseGeneratedOption.None)] 。当我运行迁移时,我可以看到标识列已删除,但是我仍然收到相同的错误消息。

I added [DatabaseGenerated(DatabaseGeneratedOption.None)] to all my properties that have a primary key. When I ran the migration I can see that the identity column is removed, But I am still getting the same error message.

当我进入SQL SEO时,仍可以在主键上看到标识列。我尝试刷新数据库。我究竟做错了什么?我唯一能做的就是进入属性并删除身份,但是为什么我不能按照上面提到的方式做呢?

When I go into SQL SEO I can still see the identity column on my primary key. I tried refreshing the database. What am I doing wrong? The only thing I can do is go into properties and remove the identity, but why can't I do it the way mentioned above?

推荐答案

在EF Core 1.1.2中,我将其用于事务处理。在我的数据库初始化程序中,将种子数据放入表中。我使用了此EF6答案中的技术。以下是代码示例:

In EF Core 1.1.2, I got this to work with transactions. In my "database initializer" that put seed data into the tables. I used the technique from this EF6 answer. Here's a sample of the code:

using (var db = new AppDbContext())
using (var transaction = db.Database.BeginTransaction())
{
    var user = new User {Id = 123, Name = "Joe"};
    db.Users.Add(user);
    db.Database.ExecuteSqlCommand("SET IDENTITY_INSERT MyDB.Users ON;");
    db.SaveChanges();
    db.Database.ExecuteSqlCommand("SET IDENTITY_INSERT MyDB.Users OFF");
    transaction.Commit();
}

这篇关于如何在.net核心中打开身份插入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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