EF trying to Insert into Identity field

This topic was automatically closed 365 days after the last reply. New replies are no longer allowed.
5 years ago
nopCommerce version: 4.1

Steps to reproduce the problem:

Nop.Core.Domain added

namespace Nop.Core.Domain.Unfreighted
{
    public partial class XFeatures : BaseEntity
    {
        /// <summary>
        /// Gets or sets the feature id
        /// </summary>
        public int FID { get; set; }

        /// <summary>
        /// Gets or sets the Y
        /// </summary>
        public double Y { get; set; }

        /// <summary>
        /// Gets or sets the X
        /// </summary>
        public double X { get; set; }

    }
}


Added Mapping

using Nop.Core.Domain.Unfreighted;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;

namespace Nop.Data.Mapping.Unfreighted
{
    public partial class XFeaturesMap : NopEntityTypeConfiguration<XFeatures>
    {
        /// <summary>
        /// Configures the entity
        /// </summary>
        /// <param name="builder">The builder to be used to configure the entity</param>
        public override void Configure(EntityTypeBuilder<XFeatures> builder)
        {
            builder.ToTable(nameof(XFeatures));
            builder.HasKey(c => c.Id);          

            base.Configure(builder);
        }

    }
}


and my service, I also added IXFeaturesService

namespace Nop.Services.Unfreighted
{
    public partial class XFeaturesService : IXFeaturesService
    {
        private readonly IRepository<XFeatures> _xFeaturesRepository;
        private readonly IDbContext _dbContext;

        public XFeaturesService(IRepository<XFeatures> xFeaturesRepository, IDbContext dbContex)
        {
            this._xFeaturesRepository = xFeaturesRepository;
            this._dbContext = dbContex;
        }

        public virtual void SPMain()
        {
            XFeatures lp = new XFeatures();
            string fileName = "xxx.shp";
            string path = Path.Combine(Environment.CurrentDirectory, @"wwwroot\files\xFeatures\", fileName);
            Shapefile importedShapeFile = Shapefile.OpenFile(path);
            for (int i = 0; i < importedShapeFile.DataTable.Rows.Count; i++)
            {

                // Get the feature
                IFeature feature = importedShapeFile.Features.ElementAt(i);
                lp.FID = feature.Fid;
                foreach(var x in feature.Coordinates)
                {
                    lp.X = x.X;
                    lp.Y = x.Y;
                    _xFeaturesRepository.Insert(lp);
                }


            }

        }


    }
}


and I am receiving;


Microsoft.EntityFrameworkCore.DbUpdateException: An error occurred while updating the entries. See the inner exception for details. ---> System.Data.SqlClient.SqlException: Cannot insert explicit value for identity column in table 'XFeatures' when IDENTITY_INSERT is set to OFF. at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action1 wrapCloseInAction) at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose) at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady) at System.Data.SqlClient.SqlDataReader.TryConsumeMetaData() at System.Data.SqlClient.SqlDataReader.get_MetaData() at System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString) at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async, Int32 timeout, Task& task, Boolean asyncWrite, SqlDataReader ds) at System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior) at Microsoft.EntityFrameworkCore.Storage.Internal.RelationalCommand.Execute(IRelationalConnection connection, DbCommandMethod executeMethod, IReadOnlyDictionary2 parameterValues) at Microsoft.EntityFrameworkCore.Storage.Internal.RelationalCommand.ExecuteReader(IRelationalConnection connection, IReadOnlyDictionary2 parameterValues) at Microsoft.EntityFrameworkCore.Update.ReaderModificationCommandBatch.Execute(IRelationalConnection connection) --- End of inner exception stack trace --- at Microsoft.EntityFrameworkCore.Update.ReaderModificationCommandBatch.Execute(IRelationalConnection connection) at Microsoft.EntityFrameworkCore.Update.Internal.BatchExecutor.Execute(DbContext _, ValueTuple2 parameters) at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerExecutionStrategy.Execute[TState,TResult](TState state, Func3 operation, Func3 verifySucceeded) at Microsoft.EntityFrameworkCore.Update.Internal.BatchExecutor.Execute(IEnumerable1 commandBatches, IRelationalConnection connection) at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChanges(IReadOnlyList1 entriesToSave) at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChanges(Boolean acceptAllChangesOnSuccess) at Microsoft.EntityFrameworkCore.DbContext.SaveChanges(Boolean acceptAllChangesOnSuccess) at Nop.Data.EfRepository`1.Insert(TEntity entity) in
5 years ago
I noticed Id is always 0.
5 years ago
I found a workaround;

on my mapping, instead of;

builder.ToTable(nameof(XFeatures));
builder.HasKey(c => c.Id);


I used

builder.ToTable(nameof(XFeatures));
builder.Property(c => c.Id).UseSqlServerIdentityColumn();


and it works.
5 years ago
Is there any other approach to solve this issue?
4 years ago
builder.Property(c=> c.Id).ValueGeneratedNever();

reference link: https://github.com/aspnet/EntityFrameworkCore/issues/14968
4 years ago
or try this one if still facing issue. I hope this help u.

using (var identityContext = new IdentityDatabase(identityOptions))
{
    Console.WriteLine("Settings Identity Insert on");
    identityContext.Database.ExecuteSqlCommand("SET IDENTITY_INSERT dbo.ClientGroups ON");

    identityContext.SaveChanges();

    Console.WriteLine("Setting Identity Insert off");
    identityContext.Database.ExecuteSqlCommand("SET IDENTITY_INSERT dbo.ClientGroups OFF");
}
This topic was automatically closed 365 days after the last reply. New replies are no longer allowed.