0
votes

What I'm trying to do:

I'm trying to save multiple descriptions of a candidate, And foreach one show them in the Description View accordingly.

Here is my Controller:

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);
    }

And Also here is my Model of the 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>();
    }

 }

And here is my View:

 @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>

The Catch methos is throwing an exception, and I do not understand why.

   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.");
            }

The exception is :

{Microsoft.EntityFrameworkCore.DbUpdateException: An error occurred while updating the entries. See the inner exception for details. ---> System.Data.SqlClient.SqlException: Cannot insert explicit value for identity column in table 'Candidates' when IDENTITY_INSERT is set to OFF. at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action1 wrapCloseInAction) at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action1 wrapCloseInAction) at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose) at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady) at System.Data.SqlClient.SqlDataReader.TryConsumeMetaData() at System.Data.SqlClient.SqlDataReader.get_MetaData() at System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString) at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async, Int32 timeout, Task& task, Boolean asyncWrite, SqlDataReader ds) at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean 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 parameterValues) at Microsoft.EntityFrameworkCore.Storage.Internal.RelationalCommand.ExecuteReader(IRelationalConnection connection, 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 parameters) at Microsoft.EntityFrameworkCore.Storage.Internal.SqlServerExecutionStrategy.Execute[TState,TResult](TState state, Func3 operation, Func3 verifySucceeded) at Microsoft.EntityFrameworkCore.Update.Internal.BatchExecutor.Execute(IEnumerable1 commandBatches, IRelationalConnection connection) at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChanges(IReadOnlyList1 entriesToSave) at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChanges(Boolean acceptAllChangesOnSuccess) at Microsoft.EntityFrameworkCore.DbContext.SaveChanges(Boolean acceptAllChangesOnSuccess) at HCCBPOHR.Web.Controllers.HomeController.CandidateHistoryPost(Candidate candidate, Int32 Id) in C:\Users\137258\Documents\hccbpohr\src\Web\Controllers\HomeController.cs:line 628}

1
Please uncomment ex and provide the DbUpdateException details. - Dan Wilson
Having a look at what the exception is actually telling you would be a good starting point. Would also help us help you if it is still not letting you sort the problem out. - PaulF
@PaulF I can't get the DbUpdateException, it doesnt have any value - Dorin Munteanu
Could you explain what are you trying to achieve and what is the logic behind of your code? - octavioccl
Well if you are getting an exception thrown that is caught by that catch statement - there will be information in the DbUpdateException. - PaulF

1 Answers

0
votes

In the exception, it says that An error occurred while updating the entries. See the inner exception for details. ---> System.Data.SqlClient.SqlException: Cannot insert explicit value for identity column in table 'Candidates' when IDENTITY_INSERT is set to OFF.

This means that in the SQL, you cannot insert in the table the value of the primary key as you have set it to identity key (for e.g. IDENTITY(1,1)). Most probably, the key will be ID in your case. In c# code, add an attribute over the field in the model class.

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