Updating Nested Objects in Entity Framework

.net c# entity-framework entity-framework-6

Question

In recent times, I've learned that EF doesn't update nested objects. I've been trying to find out how to accomplish this for a few days, but I'm having trouble.

I have an item.

public class ProjectEntity : AuditableEntity<int>
{

    public string CustumerCompany { get; set; }
    public string CustomerRepresentative { get; set; }

    public string ProjectTitle { get; set; }
    public string WwsNumber { get; set; }

    [ForeignKey("ParentProjectId")]
    public virtual ProjectEntity ParentProject { get; set; }

    public int? ParentProjectId { get; set; }

    public virtual ICollection<ProjectServicesEntity> Service { get; set; }
}

Afterward, Service object

public class ProjectServicesEntity : AuditableEntity<int>
{
    /// <summary>
    /// Service Number
    /// </summary>
    public int Number { get; set; }
    /// <summary>
    /// Service Name
    /// </summary>
    public string Name { get; set; }

    /// <summary>
    /// Positions
    /// </summary>
    public virtual ICollection<ProjectPositionsEntity> Positions { get; set; }

    [ForeignKey("ProjectId")]
    public virtual ProjectEntity Project { get; set; }

    public int ProjectId { get; set; }
}

as well as Positions object:

public class ProjectPositionsEntity : AuditableEntity<int>
{
    /// <summary>
    /// Position number
    /// </summary>
    public int Number { get; set; }

    /// <summary>
    /// Position Name
    /// </summary>
    public string Name { get; set; }

    /// <summary>
    /// Organization Unit for position
    /// </summary>
    public virtual ICollection<ProjectsOutsourcedPositionEntity> OrganizationUnit { get; set; }
    /// <summary>
    /// Represents if position is outsourced
    /// </summary>
    public bool OutSource { get; set; }
    /// <summary>
    /// Comments for position
    /// </summary>
    public string Remarks { get; set; }

    [ForeignKey("ServiceId")]
    public virtual ProjectServicesEntity Service { get; set; }

    public int ServiceId { get; set; }

}}

And this is how I update:

public void Update(T entity)
    {

            DbContext.Entry(entity).State = EntityState.Modified;
            DbContext.SaveChanges();
}

When I attempt to amend some data in Services or Positions on a page where all the data is shown, nothing changes. Has anybody experienced a situation like this?

As you can see, my object has a two-level nest, unlike every other example I saw, which only used nested objects that were one level deep.

1
5
1/19/2017 12:02:36 PM

Accepted Answer

ZZZ_tmp
3
1/19/2017 11:59:34 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow