如何在.net核心中打开身份插入

编程入门 行业动态 更新时间:2024-10-28 20:31:41
本文介绍了如何在核心中打开身份插入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我在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核心中打开身份插入

本文发布于:2023-11-16 17:24:03,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1606327.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:核心   身份   如何在   net

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!