Question

In my ASP.NET MVC application I use single view to edit an entity and some related data. When I pass the model to controller and mark appropriate entity as modified, related entities aren't updated in my database. Here's my code (simplified version):

Model:

class A
{
    public int ID { get; set; }
    public B SomeProperty { get; set; }
    public string AnotherProperty { get; set; }

    public A()
    {
        SomeProperty = new B();
    }
}

class B
{
    public int ID { get; set; }
    public string SomePropertyInClassB { get; set; }
}

Controller method:

public ActionResult Edit(A a)
{
    if(ModelState.IsValid)
    {
        var aEntity = _context.Entry(a);
        aEntity.State = EntityState.Modified;
        _context.SaveChanges();
    }
}

"AnotherProperty" is updated, but "SomePropertyInClassB" isn't. I've tried adding the following code to aforementioned method:

var b = aEntity.Reference(a => a.SomeProperty).CurrentValue;
var bEntity = _context.Entry(b);
bEntity.State = EntityState.Modified;

but it doesn't work.

Was it helpful?

Solution

I came up with solution.

In controller:

public ActionResult Edit(A a)
{
    if(ModelState.IsValid)
    {
        _context.Entry(a).State = EntityState.Modified;
        _context.Entry(a.SomeProperty ).State = EntityState.Modified;
        _context.SaveChanges();
    }
}

...and, what wasn't that obvious to me, in my view:

@Html.Hidden("SomeProperty.ID")
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top