简体   繁体   English

当 IDENTITY_INSERT 设置为 OFF 时,无法为标识列插入显式值。 (实体框架核心)

[英]Cannot insert explicit value for identity column when IDENTITY_INSERT is set to OFF. (Entity Framework Core)

I'm getting this error when I attempt to add a new entity into the Database.当我尝试将新实体添加到数据库时出现此错误。 The entity name is DestuffedContainer .实体名称是DestuffedContainer The definition of this entity and related entities is below:该实体及相关实体的定义如下:

DestuffedContainer:卸货容器:

[Table("DestuffedContainer")]
public class DestuffedContainer
{
    public long DestuffedContainerId { get; set; }
    public int Index { get; set; }
    public string Description { get; set; }
    public int? PackageQuantity { get; set; }
    public string PackageType { get; set; }
    public double? CBM { get; set; }
    public string Location { get; set; }
    public string MarksAndNumber { get; set; }
    public int? ManifestWeight { get; set; }
    public int? FoundWeight { get; set; }
    public int? ManifestQuantity { get; set; }
    public string ConsigneeName { get; set; }
    public string Remarks { get; set; }
    public string InvoiceFound { get; set; }
    public string PackageFound { get; set; }
    public long TellySheetId { get; set; }
    public TellySheet TellySheet { get; set; }
    public long ContainerIndexId { get; set; }
    public ContainerIndex ContainerIndex { get; set; }
}

TellySheet:电视表:

[Table("TellySheet")]
public class TellySheet
{
    public TellySheet()
    {
        DestuffedContainers = new List<DestuffedContainer>();
    }

    public long TellySheetId { get; set; }
    public string TellyClerk { get; set; }
    public DateTime? DestuffDate { get; set; }
    public string DayNight { get; set; }
    public long ShippingAgentId { get; set; }
    public ShippingAgent ShippingAgent { get; set; }

    public List<DestuffedContainer> DestuffedContainers { get; set; }
}

ContainerIndex:容器索引:

[Table("ContainerIndex")]
public class ContainerIndex
{
    public long ContainerIndexId { get; set; }
    public string BLNo { get; set; }
    public int? IndexNo { get; set; }
    public double? BLGrossWeight { get; set; }
    public string Description { get; set; }
    public string MarksAndNumber { get; set; }
    public string ShippingLine { get; set; }
    public bool? IsDestuffed { get; set; }
    public string AuctionLotNo { get; set; }
    public long? ContainerId { get; set; }

    public Container Container { get; set; }
    public DeliveryOrder DeliveryOrder { get; set; }
    public OrderDetail OrderDetail { get; set; }
    public DestuffedContainer DestuffedContainer { get; set; }
    public Auction Auction { get; set; }
}

The error occurs in the below lines of code when I try to add the list of destuffed containers:当我尝试添加已卸货的容器列表时,以下代码行中出现错误:

 var dstfContainers = new List<DestuffedContainer>();
 _tellySheetRepo.Add(tellySheet);

 foreach (var container in containers)
 {
     var destuff = new DestuffedContainer
            {
                TellySheetId = tellySheet.TellySheetId,
                ContainerIndexId = container.ContainerIndexId,
                Index = container.IndexNumber ?? 0,
                Description = container.Description,
                PackageQuantity = container.Package,
                PackageType = container.PackageType,
                CBM = container.CBM,
                ManifestWeight = container.ManifestWeight > 0 ? Convert.ToInt32(container.ManifestWeight) : 0,
                FoundWeight = container.FoundWeight > 0 ? Convert.ToInt32(container.FoundWeight) : 0,
                MarksAndNumber = container.MarksAndNumber,
                Location = container.Location,
                Remarks = container.Remarks,
                InvoiceFound = container.InvoiceFoud,
                PackageFound = container.PackageFoud
            };

    dstfContainers.Add(destuff);

    var index = _cIndexRepo.Find(container.ContainerIndexId);

    if (index != null)
    {
        index.IsDestuffed = true;
        _cIndexRepo.Update(index);
    }
}

_destuffRepo.AddRange(dstfContainers);

I'm not sure what this error means as I'm not explicitly specifying the primary key value of the destuffedcontainer entity and by default it's 0. Entity Framework should pick this up as an insert but instead it throws an error.我不确定这个错误是什么意思,因为我没有明确指定 destuffedcontainer 实体的主键值,默认情况下它是 0。实体框架应该把它作为插入来选择,但它会抛出一个错误。

It was working fine few days ago but I'm not sure what has changed since causing this error.几天前它工作正常,但我不确定自导致此错误以来发生了什么变化。

I'm using Entity Framework Core for modeling my entities.我正在使用 Entity Framework Core 对我的实体进行建模。 I've tried several solutions but none of them seem to work.我已经尝试了几种解决方案,但似乎都没有奏效。 I'd appreciate any help to resolve this issue.我很感激能帮助解决这个问题。

EDIT编辑

It seems that when I assign the ContainerIndexId value which is the foreign key in DestuffedContainer table to the entity, I get this error.似乎当我将 DestuffedContainer 表中的外键 ContainerIndexId 值分配给实体时,出现此错误。 I'm not sure how it's relevant.我不确定它是如何相关的。

For future readers.对于未来的读者。

I had the reverse problem.我遇到了相反的问题。 I did NOT want IDENTITY to be auto-on.我不希望 IDENTITY 自动开启。

So something like this: (very simple fluent mapping)所以像这样:(非常简单的流畅映射)

        builder.HasKey(ent => ent.MyColumnWhichIsTheKey);

I had to add this line (ValueGeneratedNever) to keep IDENITY to be off (on purpose "off"):我不得不添加这一行 (ValueGeneratedNever) 以保持 IDENITY 关闭(故意“关闭”):

        builder.HasKey(ent => ent.MyColumnWhichIsTheKey);
        builder.Property(ent => ent.MyColumnWhichIsTheKey).ValueGeneratedNever();

See:看:

https://docs.microsoft.com/en-us/dotnet/api/microsoft.entityframeworkcore.metadata.builders.propertybuilder.valuegeneratednever?view=efcore-3.1 https://docs.microsoft.com/en-us/dotnet/api/microsoft.entityframeworkcore.metadata.builders.propertybuilder.valuegeneratednever?view=efcore-3.1

Other hints:其他提示:

using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;

and

<PackageReference Include="Microsoft.EntityFrameworkCore" Version="3.1.3" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Relational" Version="3.1.3" />

The error says that you can't insert data on the IDENTITY column because doing so is disabled.该错误表示您无法在 IDENTITY 列上插入数据,因为这样做已被禁用。

You can enable this behaviour by doing您可以通过执行启用此行为

SET IDENTITY_INSERT [ [ database_name . ] schema_name . ] table_name { ON | OFF }

MSDN link MSDN链接

As you're working with entity framework core you will have to:当您使用实体框架核心时,您必须:

 context.Database.ExecuteSqlCommand("SET IDENTITY_INSERT dbo.DestuffedContainer ON"); context.SaveChanges(); context.Database.ExecuteSqlCommand("SET IDENTITY_INSERT dbo.DestuffedContainer OFF");

> Explicit values into SQL Server IDENTITY columns > 显式值到 SQL Server IDENTITY 列中

EDIT I'm sorry I failed to understand you weren't providing a value.编辑对不起,我没能理解你没有提供价值。

Then make sure your column is marked as IDENTITY for the model.然后确保您的列标记为模型的 IDENTITY。 I see you're using attributes to tell efcore how to name your table.我看到您正在使用属性来告诉 efcore 如何命名您的表。 As long as you're not using the conventional Id name for your key property, you need to make it explicit by using [Key] atribute on your entity class, on top of your property like:只要您不为键属性使用传统的Id名称,您就需要通过在实体类上使用[Key]属性来使其显式,在您的属性之上,例如:

[Key]
public long DestuffedContainerId { get; set; }

or instead use the FluentAPI inside your context class:或者在您的上下文类中使用 FluentAPI:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
 ...
    modelBuilder
    .Entity<DestuffedContainer>()
    .Property(d => d.DestuffedContainerId)
    .ValueGeneratedOnAdd() 

    modelBuilder
    .Entity<DestuffedContainer>()
    .HasKey(d => d.DestuffedContainerId)
 ...
}

also check sql server table definition and make sure the field named as your property is set as IDENTITY , it will be for sure given the error you got but it's worth checking.还要检查 sql server 表定义,并确保将命名为您的属性的字段设置为IDENTITY ,鉴于您遇到的错误,它肯定会出现,但值得检查。

Just in case someone finds this issue in 2021, with EF Core 5.x, I struggled with this for hours, and my solution wasn't found after a lot of searching.以防万一有人在 2021 年发现这个问题,使用 EF Core 5.x,我为此苦苦挣扎了几个小时,经过大量搜索后没有找到我的解决方案。

In my case I had an existing database and used the EF Core scaffolding command to create the DB Context and associated model classes for me.就我而言,我有一个现有的数据库,并使用 EF Core 脚手架命令为我创建 DB 上下文和关联的模型类。 When trying to insert a new TimeEntry into my TimeEntry table in the database like this:当尝试将新的 TimeEntry 插入数据库中的 TimeEntry 表时,如下所示:

TimeEntry timeEntry = new TimeEntry
        {
            EmployeeId = Emp.Id,
            ScheduleTypeId = SchedTypeId,
            FacilityId = FacilityId,
            DateTimeIn1 = DateTimeIn1,
            DateTimeIn2 = DateTimeIn2,
            DateTimeIn3 = DateTimeIn3,
            DateTimeIn4 = DateTimeIn4,
            DateTimeIn5 = DateTimeIn5,
            DateTimeIn6 = DateTimeIn6,
            DateTimeIn7 = DateTimeIn7,
            DateTimeOut1 = DateTimeOut1,
            DateTimeOut2 = DateTimeOut2,
            DateTimeOut3 = DateTimeOut3,
            DateTimeOut4 = DateTimeOut4,
            DateTimeOut5 = DateTimeOut5,
            DateTimeOut6 = DateTimeOut6,
            DateTimeOut7 = DateTimeOut7,
            Day1TotalHours = day1TotalHoursDecimal,
            Day2TotalHours = day2TotalHoursDecimal,
            Day3TotalHours = day3TotalHoursDecimal,
            Day4TotalHours = day4TotalHoursDecimal,
            Day5TotalHours = day5TotalHoursDecimal,
            Day6TotalHours = day6TotalHoursDecimal,
            Day7TotalHours = day7TotalHoursDecimal,
            WeekStartDate = StartDateForWeek,
            WeekTotalHours = WeekTotalHoursDecimal
        };
        db.TimeEntries.Add(timeEntry);
        db.SaveChanges();

I was getting this error, even though I wasn't explicitly trying to insert the Id.我收到此错误,即使我没有明确尝试插入 Id。 After many attempts I finally figured out how to fix it, tried everything from every post I could find but nothing worked.经过多次尝试,我终于找到了解决方法,尝试了我能找到的每个帖子中的所有内容,但没有任何效果。 This code fixed my issue within my DbContext class for the id field:此代码在我的 DbContext 类中为 id 字段修复了我的问题:

modelBuilder.Entity<TimeEntry>(entity =>
        {
            entity.ToTable("TimeEntry");

            entity.Property(e => e.Id).HasColumnName("id").ValueGeneratedOnAdd(); // <-- This fixed it for me

Also please note that, following other posts, I also have this set up in my TimeEntry model class, not sure if it matters or not to avoid this error:另请注意,在其他帖子之后,我也在我的 TimeEntry 模型类中设置了此设置,不确定是否要避免此错误:

public partial class TimeEntry
{
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    [Key]
    public int Id { get; set; } // rest of code removed for brevity

I really hope this helps someone out there in the future, was driving me crazy.我真的希望这可以帮助将来的某个人,这让我发疯了。

a solution better than the selected answer if you want to keep Identity_Insert turned off and allow manual insertion at your OnModelCreating method on your defined Application Context如果您想关闭 Identity_Insert 并允许在您定义的应用程序上下文上的 OnModelCreating 方法中手动插入,则该解决方案比所选答案更好

this is using EF Core for NET 5.0这是使用 EF Core for NET 5.0

      modelBuilder.Entity<EntityType>().HasKey(x => x.KeyWithIdentityValue);
      modelBuilder.Entity<EntityType>().Property(x => x.KeyWithIdentityValue).ValueGeneratedOnAdd();```

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 {“当IDENTITY_INSERT设置为OFF时,无法在表&#39;Cantact&#39;中为标识列插入显式值。”} - {“Cannot insert explicit value for identity column in table 'Cantact' when IDENTITY_INSERT is set to OFF.”} “当IDENTITY_INSERT设置为OFF时,无法为表&#39;Movies&#39;中的标识列插入显式值。” - “Cannot insert explicit value for identity column in table 'Movies' when IDENTITY_INSERT is set to OFF.” “当IDENTITY_INSERT设置为OFF时,无法为表{Tags}中的标识列插入显式值。” - “Cannot insert explicit value for identity column in table {Tags} when IDENTITY_INSERT is set to OFF.” 实体框架:当IDENTITY_INSERT设置为OFF时,无法为表&#39;[table]&#39;中的标识列插入显式值 - Entity Framework: Cannot insert explicit value for identity column in table '[table]' when IDENTITY_INSERT is set to OFF 实体框架核心:当IDENTITY_INSERT设置为OFF时,无法为表&#39;Relation&#39;中的Identity列插入显式值 - Entity framework core: Cannot insert explicit value for identity column in table 'Relation' when IDENTITY_INSERT is set to OFF Entity Framework Core 6 - 当 IDENTITY_INSERT 设置为 OFF 时,无法在表“角色”中插入标识列的显式值 - Entity Framework Core 6 - Cannot insert explicit value for identity column in table 'Roles' when IDENTITY_INSERT is set to OFF 当IDENTITY_INSERT设置为OFF时,获取“无法在表&#39;OrderPromo&#39;中为标识列插入显式值”。 在桌子上没有身份 - Getting 'Cannot insert explicit value for identity column in table 'OrderPromo' when IDENTITY_INSERT is set to OFF.' on table with NO Identity 当 IDENTITY_INSERT 设置为 OFF 时,无法在“DentalProcedures”中插入标识列的显式值。 EF代码优先 - Cannot insert explicit value for identity column in 'DentalProcedures' when IDENTITY_INSERT is set to OFF. EF code first 当IDENTITY_INSERT设置为OFF时,无法在TABLE中为Identity列插入显式值; .NET Core 2.1 - Cannot insert explicit value for identity column in TABLE when IDENTITY_INSERT is set to OFF; .NET Core 2.1 使用现有数据库和实体框架的代码优先:当IDENTITY_INSERT设置为OFF时,无法为表中的标识列插入显式值 - Code First With Existing Database, Entity Framework: Cannot insert explicit value for identity column in table when IDENTITY_INSERT is set to OFF
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM