下面的代碼工作正常,直到添加組合鍵。添加複合鍵後,我只能編輯現有的記錄,無法添加新的記錄。我想Code
和CompanyId
列成爲組合鍵。添加合成後,我無法保存記錄
這是錯誤:
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");
}
}
錯誤消息很明顯,您嘗試在IDENTITY_INSERT設置爲打開時將值插入標識列。 – Sami
如何使用FluentAPI設置'on'?通過啓用identity_insert將解決我的問題? –
閱讀[this](https://docs.microsoft.com/en-us/sql/t-sql/statements/set-identity-insert-transact-sql) – Sami