设置Identity_insert tableName使用EF Core 6.0不起作用
我的业务情况是:我们正在尝试从一个供应商转移到我们自己的解决方案。目前,我们正在构建解决方案。
构建我们自己的解决方案需要ticketid
自动增加的身份列。
我们还使用供应商的API从供应商中导入数据,该供应商的API具有已经分配的TicketID
我们想要保留的。
为此,我们需要手动插入ticketid
,以跟踪数据库和供应商数据库之间的ID。我该怎么做。我尝试了以下内容,但似乎不起作用。
我看了看这个 Microsoft文章
如果有人可以提出解决方案或让我知道我的工作不正确的话,会很感激。
不确定序列是否会在此过程中有所帮助。
我有一张名为“售票”的表
public partial class Ticket
{
public long TicketId { get; set; }
...
}
public void Configure([NotNull] EntityTypeBuilder<Ticket> builder)
{
builder.HasKey(_ => _.TicketId);
builder.Property(e => e.TicketId).ValueGeneratedNever();
....
}
,在服务中,我正在尝试保存数据,如下所示,
dbContext.Database.ExecuteSqlRaw("SET IDENTITY_INSERT Corporate.Ticket ON");
dbContext.SaveChanges();
dbContext.Database.ExecuteSqlRaw("SET IDENTITY_INSERT Corporate.Ticket Off");
这总是会引发错误
Microsoft.EntityFrameworkCore.Realational:保存实体更改时发生了错误。有关详细信息,请参见内部例外。核心Microsoft SQLCLCLIENT数据提供商:当SIDENTITY_INSERT设置为OFF时,表“票证”中的身份列无法插入显式值。
在实体中,我试图
builder.Property(e => e.TicketId).ValueGeneratedOnAdd();
设置
builder.Property(e => e.TicketId).ValueGeneratedNever();
My business scenario is: we are trying to move from one vendor to our own solution. Currently, we are building the solution.
Building our own solution requires the identity column for TicketId
to auto incremented.
We are also importing the data from the vendor using vendor's API, which has an TicketId
already assigned which we want to keep.
For this we need to insert the TicketId
manually to keep track of the Id between our database and vendor's database. How do I do that. I tried the following and doesn't seem to work.
I looked at this Microsoft article
Would appreciate, if anyone can propose a solution or let me know what I'm not doing correctly.
Not sure whether Sequences will help in the process.
I have a table called Ticket with the following
public partial class Ticket
{
public long TicketId { get; set; }
...
}
public void Configure([NotNull] EntityTypeBuilder<Ticket> builder)
{
builder.HasKey(_ => _.TicketId);
builder.Property(e => e.TicketId).ValueGeneratedNever();
....
}
and in the Service, I'm trying to save the data as follows
dbContext.Database.ExecuteSqlRaw("SET IDENTITY_INSERT Corporate.Ticket ON");
dbContext.SaveChanges();
dbContext.Database.ExecuteSqlRaw("SET IDENTITY_INSERT Corporate.Ticket Off");
This always throws an error
Microsoft.EntityFrameworkCore.Relational: An error occurred while saving the entity changes. See the inner exception for details. Core Microsoft SqlClient Data Provider: Cannot insert explicit value for identity column in table 'Ticket' when IDENTITY_INSERT is set to OFF.
In the entity, I had tried to set
builder.Property(e => e.TicketId).ValueGeneratedOnAdd();
as well as
builder.Property(e => e.TicketId).ValueGeneratedNever();
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论