AyakoS
AyakoS

Reputation: 221

How to save one specific value in database

I have this Issue class. Is there

public class Issue
{
    public int IssueId { get; set; }

    [Required]
    public string ReporterName { get; set; }

    [Required]
    public string Description { get; set; }

    public int? IssueTypeId { get; set; }

    public virtual IssueType type { get; set; }
}

Then this is the view I have so I can change the value of the IssueTypeId. However when I try to save it in the database with that code in the controller, I am having an error saying that the ReporterName and Description are still required. How can I only update one specific value in database, in this case IssueTypeId?

@using (Html.BeginForm())
{
   @Html.AntiForgeryToken()

<div class="form-horizontal">
    <h4>Issue</h4>
    <hr />
    @Html.ValidationSummary(true, "", new { @class = "text-danger" })
    @Html.HiddenFor(model => model.IssueId)

    <div class="form-group">
        @Html.LabelFor(model => model.IssueTypeId, "IssueTypeId", htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.DropDownList("IssueTypeId", null, htmlAttributes: new { @class = "form-control" })
            @Html.ValidationMessageFor(model => model.IssueTypeId, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        <div class="col-md-offset-2 col-md-10">
            <input type="submit" value="Save" class="btn btn-default" />
        </div>
    </div>
</div>

}

My code in controller

public ActionResult AssignFixer(int issueId, int issueTypeId)
    {
        var issue = new Issue { IssueId = issueId , IssueTypeId= issueTypeId};

        using (var newContext = new SystemContext())
        {
            newContext.Issues.Attach(issue);
            newContext.Entry(issue).Property(i => i.IssueTypeId).IsModified = true;
            newContext.SaveChanges();
        }
        return View(issue);
    }

Upvotes: 1

Views: 89

Answers (1)

PM.
PM.

Reputation: 1721

Instead of attaching the issue in newContext.Issues. First get the instance and then update it. Like:

var existingIssue = newContext.Issues.Where(i => i.IssueId == issueId).FirstOrDefault();

existingIssue.IssueTypeId = issueTypeId;

newContext.SaveChanges();

Upvotes: 3

Related Questions