2017-11-18 194 views
0

下面的代碼工作正常,直到添加組合鍵。添加複合鍵後,我只能編輯現有的記錄,無法添加新的記錄。我想CodeCompanyId列成爲組合鍵。添加合成後,我無法保存記錄

這是錯誤:

Cannot insert explicit value for identity column in table 'CostCenters' when IDENTITY_INSERT is set to 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"); 
     } 
    } 
+0

錯誤消息很明顯,您嘗試在IDENTITY_INSERT設置爲打開時將值插入標識列。 – Sami

+0

如何使用FluentAPI設置'on'?通過啓用identity_insert將解決我的問題? –

+1

閱讀[this](https://docs.microsoft.com/en-us/sql/t-sql/statements/set-identity-insert-transact-sql) – Sami

回答

0

Cannot insert explicit value for identity column in table 'CostCenters' when IDENTITY_INSERT is set to OFF.

錯誤信息是明確的也有幫助,你試圖將值插入到IDENTITY列,而IDENTITY_INSERT設置爲OFF

我建議刪除該值,讓SQL服務器做的工作,但如果你堅持要插入值,那麼你應該設置IDENTITY_INSERTON並再次將其設置爲OFF完成剛過:

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