下面的代码工作正常,直到添加复合键。复合键添加后,我只能编辑现有记录,无法添加新记录。我希望Code
和CompanyId
列成为复合键。
这是错误:
无法在表中插入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");
}
}
答案 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