2

I have a Project model that I want to edit. The problem is that my foreign key to the owner is set to null after editing it.

Also when I create a project int the post action I add the owner manually.

I don't understand why my foreign key for the owner is reset after I edit it and I don't know a way to tell it to leave it alone.

What is the correct way to do this?

public class Project
{
    public int Id { get; set; }

    public string Name { get; set; }

    public string Description { get; set; }

    public string OwnerId { get; set; }

    [ForeignKey("OwnerId")]
    public virtual ApplicationUser Owner { get; set; }
}


    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> Edit(int id,     [Bind("Id,Description,Name")] Project project)
    {
        if (id != project.Id)
        {
            return NotFound();
        }

        if (ModelState.IsValid)
        {
            try
            {
                _context.Update(project);
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!ProjectExists(project.Id)) 
                    return NotFound();
                else
                    throw;
            }
            return RedirectToAction("Index");
        }
        return View(project);
    }
korn3l
  • 143
  • 10

1 Answers1

3

The problem is that your [Bind] attribute tells the ModelBinder to not bind the OwnerId back to the Project used in the controller:

public async Task<IActionResult> Edit(int id,     [Bind("Id,Description,Name")] Project project)

So your OwnerId will be null when you save the Project, and EF will remove the previous Owner.

You could roundtrip the previous owner using a hidden field for the OwnerId on your View and include it in the [Bind] attribute.

An even cleaner way would be to use a ViewModel for the postdata, load the existing Project from the database in your controller and only map the properties that you want to update from your ViewModel to your Entity Model. Then you can not overwrite any properties of the Entity Model that you do not explicitly want to overwrite.

Georg Patscheider
  • 9,357
  • 1
  • 26
  • 36