【问题标题】:DbUpdateException "Unable to save changes"DbUpdateException“无法保存更改”
【发布时间】:2018-07-03 15:27:09
【问题描述】:

我想做的事:

我正在尝试保存一个候选人的多个描述,并在每个描述视图中相应地显示它们。

这是我的控制器:

public IActionResult CandidateHistory(int Id)
    {

        using (var applicationcontext = new ApplicationContext())
        {
            var candidate = 
  applicationcontext.Candidates.AsNoTracking().Include(q => 
         q.DescriptionList).Single(q => q.Id == Id);
            if (candidate == null)
            {
                return NotFound();
            }
            applicationcontext.Candidates.Add(candidate);

            return View(candidate);
        }
    }

    [HttpPost, ActionName("CandidateHistory")]
    [ValidateAntiForgeryToken]
    public IActionResult CandidateHistoryPost([Bind("Description, Title, 
     DateOfDescription, Saving")]Candidate candidate, int Id)
    {
        try
        {
            if (ModelState.IsValid)
            {
                using (var applicationContext = new ApplicationContext())
                {
                    var candidates = 
        applicationContext.Candidates.AsNoTracking().Include(q => 
           q.DescriptionList).Single(q => q.Id == Id);
                    //candidates.Description = candidate.Description;
                    //candidates.Saving = candidate.Saving;
                    //candidates.Title = candidate.Title;
                    //candidates.DateOfDescription = 
              candidate.DateOfDescription;
                    //candidate.DescriptionList.Add(candidates);


                    var guardar = candidate;
                    candidates.Saving = guardar.Saving;
                    candidates.Title = guardar.Title;
                    candidates.Description = guardar.Description;
                    candidates.DateOfDescription = guardar.DateOfDescription;




                    candidate = candidates;
                    candidates.DescriptionList.Add(candidate);
                    candidate.DescriptionList = candidates.DescriptionList;
                    applicationContext.Candidates.Add(candidate);
                    applicationContext.SaveChanges();

                    return RedirectToAction("CandidateHistory");
                }
            }
        }
        catch (DbUpdateException /* ex */)
        {
            //Log the error (uncomment ex variable name and write a log.
            ModelState.AddModelError("", "Unable to save changes. " +
                "Try again, and if the problem persists " +
                "see your system administrator.");
        }

        return View(candidate);
    }

还有我的候选人模型:

 public class Candidate : BaseEntity
 {
    public int Id { get; set; }
    public string Name { get; set; }
    public int Number { get; set; }
    public string ProfileText { get; set; }
    public Byte[] CV { get; set; }
    public string CVNAME { get; set; }
    public List<Profile> ProfileList { get; set; }
    public String Description { get; set; }
    public Boolean Saving { get; set; }
    public string Title { get; set; }
    public DateTime DateOfDescription { get; set; }
    public List<Candidate> DescriptionList { get; set; }
    public Candidate()
    {
        DescriptionList = new List<Candidate>();
    }

 }

这是我的观点:

 @model HCCBPOHR.Data.Candidate

  @{
 ViewData["Title"] = "CandidateHistory";
 }

 <h2>Canidate - @Model.Name</h2>

  <label>History</label>
 <hr />

  <div class="panel panel-default">
 <div class="panel-heading">
    <i class="fa fa-clock-o fa-fw"></i> History Of @Model.Name
 </div>
 <div class="panel-body">
    @foreach (var Description in Model.DescriptionList)
    {
        @if (Model.Saving == true)
        {
            <ul class="timeline">
                <li class="timeline">
                    <div class="timeline-badge">
                        <i class="fa fa-check"></i>
                    </div>
                    <div class="timeline-panel">
                        <div class="timeline-heading">
                            <h4 class="timeline-title">@Model.Title</h4>
                            <p>
                                <small class="text-muted"><i class="fa fa- 
  clock-o"></i> @Model.DateOfDescription.ToShortDateString()</small>
                            </p>
                        </div>
                        <div class="timeline-body">
                            <p>@Model.Description</p>
                        </div>
                    </div>
                </li>
            </ul>
        }
        @if (Model.Saving == false)
        {
            <ul class="timeline">
                <li class="timeline-inverted">
                    <div class="timeline-badge">
                        <i class="fa fa-check"></i>
                    </div>
                    <div class="timeline-panel">
                        <div class="timeline-heading">
                            <h4 class="timeline-title">Title</h4>
                            <p>
                                <small class="text-muted"><i class="fa fa- 
  clock-o"></i> @Model.DateOfDescription.ToShortDateString()</small>
                            </p>
                        </div>
                        <div class="timeline-body">
                            <p>@Model.Description</p>
                        </div>
                    </div>
                </li>
            </ul>
        }
        }
   </div>
  </div>
    <button type="button" class="btn btn-primary" data-toggle="modal" data- 
   target="#exampleModal" data-whatever="@Model.Saving"> Add History 
      Description</button>
   <div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" 
  aria- 
  labelledby="exampleModalLabel" aria-hidden="true">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
        <div class="modal-body">
            <form asp-action="CandidateHistory">
                <div asp-validation-summary="ModelOnly" class="text-danger"> 
  </div>
                <div class="form-group">
                    <label asp-for="Title" class="control-label"></label>
                    <input asp-for="Title" class="form-control" />
                    <span asp-validation-for="Title" class="text-danger"> 
           </span>
                 </div>
                <div class="form-group">
                    <label asp-for="Description" class="control-label"> 
                 </label>
                    <input asp-for="Description" class="form-control" />
                    <span asp-validation-for="Description" class="text- 
              danger"></span>
                </div>
                <div class="form-group">
                    <label>Selects</label>
                    <select asp-for="Saving" class="form-control">
                        <option value="false">Candidate </option>
                        <option value="true">Hitachi</option>s
                    </select>
                </div>
                <div class="form-group">
                    <label asp-for="DateOfDescription" class="form-group" > 
           </label>
                    <input asp-for="DateOfDescription" class="form-group" />
                </div>
                <div class="form-group">
                    <input type="submit" value="Create" class="btn btn- 
       default" />
                </div>
            </form>
        </div>
        <div class="modal-footer">
            <button type="button" class="btn btn-secondary" data- 
     dismiss="modal">Close</button>

        </div>
    </div>
   </div>
   </div>

Catch 方法抛出异常,我不明白为什么。

   catch (DbUpdateException /* ex */)
            {
                //Log the error (uncomment ex variable name and write a log.
                ModelState.AddModelError("", "Unable to save changes. " +
                    "Try again, and if the problem persists " +
                    "see your system administrator.");
            }

例外是:

{Microsoft.EntityFrameworkCore.DbUpdateException:更新条目时出错。有关详细信息,请参阅内部异常。 ---> System.Data.SqlClient.SqlException:当 IDENTITY_INSERT 设置为 OFF 时,无法在表“候选人”中插入标识列的显式值。 在 System.Data.SqlClient.SqlConnection.OnError(SqlException 异常,布尔型 breakConnection,Action1 wrapCloseInAction) at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action1 wrapCloseInAction) 在 System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj,布尔调用者HasConnectionLock,布尔异步关闭) 在 System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior,SqlCommand cmdHandler,SqlDataReader dataStream,BulkCopySimpleResultSet bulkCopyHandler,TdsParserStateObject stateObj,Boolean & dataReady) 在 System.Data.SqlClient.SqlDataReader.TryConsumeMetaData() 在 System.Data.SqlClient.SqlDataReader.get_MetaData() 在 System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds,RunBehavior runBehavior,字符串 resetOptionsString) 在 System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior,RunBehavior runBehavior,布尔 returnStream,布尔异步,Int32 超时,任务和任务,布尔异步写入,SqlDataReader ds) 在 System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior,RunBehavior runBehavior,布尔 returnStream,TaskCompletionSource1 completion, Int32 timeout, Task& task, Boolean asyncWrite, String method) at System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior) at System.Data.SqlClient.SqlCommand.ExecuteDbDataReader(CommandBehavior behavior) at Microsoft.EntityFrameworkCore.Storage.Internal.RelationalCommand.Execute(IRelationalConnection connection, DbCommandMethod executeMethod, IReadOnlyDictionary2 参数值) 在 Microsoft.EntityFrameworkCore.Storage.Internal.RelationalCommand.ExecuteReader(IRelationalConnection 连接,IReadOnlyDictionary2 parameterValues) at Microsoft.EntityFrameworkCore.Update.ReaderModificationCommandBatch.Execute(IRelationalConnection connection) --- End of inner exception stack trace --- at Microsoft.EntityFrameworkCore.Update.ReaderModificationCommandBatch.Execute(IRelationalConnection connection) at Microsoft.EntityFrameworkCore.Update.Internal.BatchExecutor.Execute(Tuple2 参数) 在 Microsoft.EntityFrameworkCore.Storage.Internal.SqlServerExecutionStrategy.Execute[TState,TResult](TState 状态,Func3 operation, Func3 verifySucceeded) 在 Microsoft.EntityFrameworkCore.Update.Internal.BatchExecutor.Execute(IEnumerable1 commandBatches, IRelationalConnection connection) at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChanges(IReadOnlyList1 entriesToSave) 在 Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChanges(布尔型 acceptAllChangesOnSuccess) 在 Microsoft.EntityFrameworkCore.DbContext.SaveChanges(布尔型 acceptAllChangesOnSuccess) 在 HCCBPOHR.Web.Controllers.HomeController.CandidateHistoryPost(Candidate Candidate, Int32 Id) in C:\Users\137258\Documents\hccbpohr\src\Web\Controllers\HomeController.cs:line 628}

【问题讨论】:

  • 请取消注释ex 并提供DbUpdateException 详细信息。
  • 看看异常实际上告诉你什么将是一个很好的起点。如果仍然无法让您解决问题,我们也会帮助您。
  • @PaulF 我无法获得 DbUpdateException,它没有任何价值
  • 你能解释一下你想要实现什么以及你的代码背后的逻辑是什么?
  • 好吧,如果你抛出了一个被 catch 语句捕获的异常 - DbUpdateException 中会有信息。

标签: c# asp.net asp.net-core


【解决方案1】:

在异常中,它说An error occurred while updating the entries. See the inner exception for details. ---&gt; System.Data.SqlClient.SqlException: Cannot insert explicit value for identity column in table 'Candidates' when IDENTITY_INSERT is set to OFF.

这意味着在 SQL 中,您无法在表中插入主键的值,因为您已将其设置为标识键(例如 IDENTITY(1,1))。最有可能的是,在您的情况下,密钥将是 ID。在 C# 代码中,在模型类中的字段上添加一个属性。

[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id{ get; set; }

【讨论】:

  • 我已将该属性添加到模型类中,但仍然得到相同的异常
  • 可以分享一下你的sql结构和实体框架映射吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-02-19
  • 2016-07-07
  • 2016-09-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多