Entity Framework - Update entity but not child entity

87 Views Asked by At

In my EF 6 MVC app, I have an entity Seller which has a 1:1 relationship to SellerShippingPolicies. When I update the seller entity, EF is also attempting to update the SellerShippingPolicies entity, and I don't want this to happen.

I have the following method that updates a Seller entity:

    public Entities.Seller Save(Entities.Seller seller)
    {
        // Instantiate a helper method
        HelperMethods helper = new HelperMethods(this.UnitOfWork);

        // Map the domain entity to an EF entity
        var sellerRecord = Mapper.Map<Seller>(seller);

        // Attempt to prevent the updating of the SellerShippingPolicies entity
        helper.GetDbContext().Entry(sellerRecord.SellerShippingPolicies).State = EntityState.Detached;

        // Save the entity
        sellerRecord = helper.SaveItem<Seller>(sellerRecord);
    }

Here is the SaveItem method that gets called:

    public T SaveItem(T entity)
    {
        var row = this._dbSet.Find(GetPrimaryKeyValue(entity));
        if ( row == null )
            return AddItem(entity);
        else
            return UpdateItem(entity);
    }

And the Update method that eventually gets called:

    public T UpdateItem(T entity)
    {
        // Retrieve the current copy of the entity to be updated.
        var currentEntity = GetItem(GetPrimaryKeyValue(entity));

        // Copy the contents of the modified entity on top of the copy we just retrieved. This way EF will save everything correctly.
        currentEntity = Copy.ShallowCopy<T>(entity, currentEntity);

        this._dbContext.SaveChanges();

        return currentEntity;
    }

Not sure it's necessary, but here is the method for ShallowCopy and GetItem.

    public static T ShallowCopy<T>(object source, T target)
    {
        foreach (PropertyInfo pi in typeof(T).GetProperties())
        {
            var property = source.GetType().GetProperty(pi.Name);

            if (property == null)
                continue;

            if (property.GetSetMethod() != null)
                property.SetValue(target, pi.GetValue(source, null), null);
        }
        return target;
    }

    public T GetItem(object primaryKeyValue)
    {
        return this._dbSet.Find(primaryKeyValue);
    }

All these methods share the same context object.

You can see that I'm attempting to prevent the updating of the SellerShippingPolicies entity by setting its state to detached. This does not work. I've also tried setting the state to Unchanged. That doesn't work either. In both cases, EF attempts to update the SellerShippingPolicies entity. What am I missing?

0

There are 0 best solutions below