【问题标题】:After adding composite i wasn't able to Save Records添加复合材料后,我无法保存记录
【发布时间】:2018-05-02 03:09:09
【问题描述】:

在添加复合键之前,以下代码运行良好。添加复合键后,我只能编辑现有记录,无法添加新记录。我希望 CodeCompanyId 列成为复合键。

这是错误:

无法为表中的标识列插入显式值 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");
        }
    }

【问题讨论】:

  • 错误消息很清楚,您正尝试在 IDENTITY_INSERT 设置为 on 时向标识列插入值。
  • 如何使用 FluentAPI 设置on?通过启用 identity_insert 会解决我的问题吗?
  • 阅读this
  • 还有你为什么要尝试向标识列插入值,为什么不让 SQL Server 为你做呢?
  • 您的数据库架构与您的模型不匹配,IDENTITY 似乎在您的数据库中的 CompanyId(我假设)上,而您将 DatabaseGeneratedOption 设置为 None。从您不需要的任何列中删除身份约束,或使用身份插入(请记住显式使用事务,否则 EF 会将您的语句包装在自己的事务中,并且您的更改不会产生任何影响)插入这些。

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


【解决方案1】:

当 IDENTITY_INSERT 设置为 OFF 时,无法为表“CostCenters”中的标识列插入显式值。

错误消息也很明显很有帮助,您正尝试在 IDENTITY_INSERT 设置为 OFF 时向 IDENTITY 列插入值。

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

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

【讨论】:

    猜你喜欢
    • 2016-04-21
    • 2016-09-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-04
    • 2013-07-02
    相关资源
    最近更新 更多