添加复合后,我无法保存记录

时间:2017-11-18 12:10:40

标签: c# sql-server entity-framework asp.net-mvc-5 ef-fluent-api

下面的代码工作正常,直到添加复合键。复合键添加后,我只能编辑现有记录,无法添加新记录。我希望CodeCompanyId列成为复合键。

这是错误:

  

无法在表中插入identity列的显式值   ' CostCenters'当IDENTITY_INSERT设置为OFF时。

在SO中寻找解决方案并在线下添加(仍然没有进展):

Property(c => c.CompanyId).HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);

型号:

public class CostCenter
{
    public int Id { get; set; }
    public string Code { get; set; }
    public string Description { get; set; }
    [ScriptIgnore(ApplyToOverrides = true)]
    public virtual Company Company { get; set; }
    public int CompanyId { get; set; }
}

FluentAPI:

public CostCenterConfiguration()
    {
        HasKey(c => new { c.Code, c.CompanyId });
        Property(c => c.CompanyId)
        .HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
        Property(c => c.Code)
        .IsRequired()
        .HasMaxLength(255);
        Property(c => c.Description)
        .HasMaxLength(1200);
        HasRequired(c => c.Company)
        .WithMany(c => c.CostCenters)
        .HasForeignKey(c => c.CompanyId)
        .WillCascadeOnDelete(false);
    }

控制器:

public ActionResult Save(CostCenter costcenter)
    {
        try
        {
            if (costcenter.Id == 0)
                _context.CostCenters.Add(costcenter);
            else
            {
                var costcenterInDb = _context.CostCenters.Single(c => c.Id == costcenter.Id);
                costcenterInDb.Code = costcenter.Code;
                costcenterInDb.Description = costcenter.Description;
                costcenterInDb.CompanyId = costcenter.CompanyId;
            }
            _context.SaveChanges();
            return RedirectToAction("Index", "CostCenters");
        }
        catch (System.Data.Entity.Validation.DbEntityValidationException ex)
        {
            var error = ex.EntityValidationErrors.First().ValidationErrors.First();
            this.ModelState.AddModelError(error.PropertyName, error.ErrorMessage);
            return View("CostCenterForm");
        }
        catch (DbUpdateException e) when ((e?.InnerException?.InnerException as System.Data.SqlClient.SqlException)?.Number == 2601)
        {
            this.ModelState.AddModelError("Code", "Item with such '" + costcenter.Code + "' already exist");
            return View("CostCenterForm");
        }
    }

1 个答案:

答案 0 :(得分:0)

  

无法在表格' CostCenters'中插入标识列的显式值当IDENTITY_INSERT设置为OFF时。

错误消息显然也很有帮助,当 IDENTITY_INSERT 设置为IDENTITY时,您试图将值插入OFF列。< / p>

我建议删除该值并让SQL Server完成工作,但如果您坚持要插入值,则应将IDENTITY_INSERT设置为ON并将其设置为OFF在你完成之后再次:

SET IDENTITY_INSERT Schema.TableName ON;  
GO  
-- do your insert
SET IDENTITY_INSERT Schema.TableName OFF;  
GO