A
A
artofdev2015-04-12 22:54:50
C++ / C#
artofdev, 2015-04-12 22:54:50

Entity Framework 6 complex model update - how?

Thanks in advance to everyone who answers my question. The bottom line is this - there is a very complex model that describes the application for the delivery of goods (we are doing an internal logistics service - Web API 2 + AngularJS + Angular Material + Google Maps).
The application contains one point of departure, one car and several cargoes. Each cargo in turn contains several destinations.
DB scheme 1c732894af204304b5e86c620b2980cb.png
Question - how to implement editing of this request?
Thanks in advance for your replies!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
artofdev, 2015-04-13
@artofdev

Request handler for editing a delivery request

public async Task<IHttpActionResult> EditDeliveryBidAsync(long id, EditBid bid)
        {
            var dbBid = await DeliveryManager.GetBidAsync(id);
            if (dbBid != null)
            {
                var oldCargoIds = dbBid.Cargos.Select(c => c.Id).ToArray();
                Mapper.Map(bid, dbBid);
                if (await DeliveryManager.UpdateBidAsync(dbBid, oldCargoIds))
                    return Ok();
            }
            return BadRequest();
        }

Application manager
public async Task<bool> UpdateBidAsync(DeliveryBid bid, long[] oldCargoIds)
        {
            DbContext.Entry(bid).State = EntityState.Modified;
            await DbContext.DeliveryCargos.ForEachAsync(c =>
            {
                if (oldCargoIds.Any(o => o == c.Id))
                    DbContext.DeliveryCargos.Remove(c);
            });
            var updatedBid = await DbContext.SaveChangesAsync();
            return updatedBid > 0;
        }

In the handler, we get the Id's of all the loads that are already attached to the order, then we map the ViewModel to the database object. Next, we call the manager responsible for working with requests in the database, passing him a new model and Ids of old cargoes (which must be deleted, since Null is not allowed for the cargo key). Then we mark the old loads for deletion, tell the model that it has been modified and save the changes. Old loads are removed, new ones are added and everything works as expected.
I agree that it is not the most elegant solution, I will be glad to any comments on this issue and its solution.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question