简体   繁体   中英

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 . 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.

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. 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. 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.

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"):

        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

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.

You can enable this behaviour by doing

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

MSDN link

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

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. I see you're using attributes to tell efcore how to name your table. 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:

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

or instead use the FluentAPI inside your context class:

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.

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.

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. When trying to insert a new TimeEntry into my TimeEntry table in the database like this:

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. 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:

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:

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

this is using EF Core for NET 5.0

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM