In my code I have several lines of code which looks like this:
Insertions["sale"] = (modelEntities, entity) => modelEntities.AddToSale((Sale) entity);
It works fine when there is no such entity in database. But I want to update entity when it is already in database. It can be done via Find method and fields assignment but I want to keep a pretty code and use something like initialization from constructor or Insert-or-Update.
How can I do this?
Personally I think it is useless to build a dictionary with add/insert method delegates. It’s a lot of repetitive code. The context has generic methods to insert or update any entity object. You can even make one method that does both, for example (based on
ObjectContext):If you want you can even factor out the
keyargument by getting the key field from the EF model and doing some reflection on theentity, but that probably slows down the process remarkably.Note that an
Attachedpersisted object is ignored by this method: it is assumed that it will be saved by the context it already belongs to.