简体   繁体   中英

EF Core Insert Identity Issues

I'm using EF Core 2.2.4 and I'm trying to insert datas through an asp.net MVC page.

Here's my repository insert command:

public int InsertFatorMarkup(int empId, GmPreFamFatMkp gmPreFamFatMkp, int usuId)
        {
            using (var transaction = _GFazContext.Database.BeginTransaction())
            {
                try
                {
                    var preFamFatId = EtapaInsertFator(empId, gmPreFamFatMkp, usuId);
                    transaction.Commit();
                    return preFamFatId;
                }
                catch (Exception ex)
                {
                    transaction.Rollback();
                    throw ex;
                }
            }
        }

        //Fernando Milanez 28/11/2019
        private int EtapaInsertFator(int empId, GmPreFamFatMkp gmPreFamFatMkp, int usuId)
        {
            gmPreFamFatMkp = RecargaDeDependenciasFator(empId, gmPreFamFatMkp);

            gmPreFamFatMkp.PreFamFatId = NextFatorMkpId(gmPreFamFatMkp.PreId, empId);
            gmPreFamFatMkp.RegrasNegocio(usuId);

            _GFazContext.GmPreFamFatMkp.Add(gmPreFamFatMkp);
            _GFazContext.SaveChanges();
            return gmPreFamFatMkp.PreFamFatId;
        }

        //Fernando Milanez 28/11/2019
        private GmPreFamFatMkp RecargaDeDependenciasFator(int empId, GmPreFamFatMkp gmPreFamFatMkp)
        {
            gmPreFamFatMkp.GmPreTab = GetById(empId, gmPreFamFatMkp.PreId);
            //gmPreFamFatMkp.GmPreTab = _GFazContext.GmPreTab
            //    .FirstOrDefault(r => r.EmpId == empId && r.PreId == gmPreFamFatMkp.PreId);

            return gmPreFamFatMkp;
        }

        //Fernando Milanez 28/11/2019
        private short NextFatorMkpId(int preId, int empId)
        {
            var max = _GFazContext.GmPreFamFatMkp
                .Where(r => r.PreId == preId)
                .Select(r => (int)r.PreFamFatId)
                .DefaultIfEmpty(0)
                .Max();

            return Convert.ToInt16(max + 1);
        }

Here's my controller Get and Post methods:

 [HttpGet]
        public IActionResult FamiliaMarkupInsert(int preId)
        {
            ViewBag.returnUrl = Request.Headers["Referer"].ToString();

            var model = new PreFamFatMkpModel();
            model.Form = new GmPreFamFatMkp() { PreId = preId };
            model.Form.GmPreTab = _gmPreTabRepositorio.GetById(_empId, preId, false);
            model.FamiliaModel = new FamiliaModel();
            GetDataCombo(ref model);

            return View(model);
        }

        //Fernando Milanez 29/11/2019
        [HttpPost]
        public IActionResult FamiliaMarkupInsert(PreFamFatMkpModel model)
        {
            ViewBag.returnUrl = Request.Headers["Referer"].ToString();
            if (ModelState.IsValid)
            {
                try
                {
                    int newPreFamFatId = _gmPreTabRepositorio.InsertFatorMarkup(_empId, model.Form, _usuId);
                    return RedirectToAction("TabelaPrecoTabs", new { id = model.Form.PreId, tabName= "Markup Por Família" });
                }
                catch (Exception ex)
                {
                    ModelState.AddModelError("", ex.Message);
                    if (ex.InnerException != null) ModelState.AddModelError("", ex.InnerException.Message);
                }
            }
            GetDataCombo(ref model);
            model.Form.GmPreTab = _gmPreTabRepositorio.GetById(_empId, model.Form.PreId);
            return View(model);
        }

Here's my configuration class:

public class GmPreFamFatMkpConfigurations : IEntityTypeConfiguration<GmPreFamFatMkp>
    {
        public void Configure(EntityTypeBuilder<GmPreFamFatMkp> builder)
        {
            builder.HasKey(r => new { r.PreFamFatId });
            builder.Property(r => r.PreFamFatId).UseSqlServerIdentityColumn();

            //Monta Relacionamento 1-N - Colocar somente as dependencias, nesse caso depende da tabela de preço e do produto

            builder.HasOne(prepro => prepro.GmPreTab).WithMany(pretab => pretab.GmPreFamFatMkps).HasForeignKey(prepro => prepro.PreId);

            builder.HasOne(prefamfatmkp => prefamfatmkp.GmPreTab).WithMany(famtab => famtab.GmPreFamFatMkps).HasForeignKey(prefamfatmkp => prefamfatmkp.PreId);


        }
    }

And finally, heres my error:

Unable to enter an explicit value for the identity column in table 'GmPreFamFatMkp' when IDENTITY_INSERT is set to OFF.

The error is pretty self explanatory. You've provided a value for the column 'GmPreFamFatMkp' and it is an Identity column (guessing auto-increment) and "Identity_Insert" is off. You probably want to leave it that way. You can't provide a value for this column. Give it null or zero value and let EF and the database figure out the correct value.

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