0

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?

2
  • First the bigger picture. What is the intention of your line of code? Why the dictionary? Commented Nov 9, 2012 at 18:14
  • It is the dictionary with lambdas to add entities to database by type which stored in string. I want to add entity when there is no such entity and update if not Commented Nov 10, 2012 at 12:41

1 Answer 1

1

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):

public static void Upsert<T>(this ObjectContext context, T entity, int key)
  where T : EntityObject
{
  if (entity != null)
  {
    ObjectSet<T> objectSet = context.CreateObjectSet<T>();
    if (key > 0)
    {
      if (entity.EntityState == EntityState.Detached)
      {
        objectSet.Attach(entity);
        context.ObjectStateManager.ChangeObjectState(entity, EntityState.Modified);
      }
    }
    else
    {
      objectSet.AddObject(entity);
    }
  }
}

If you want you can even factor out the key argument by getting the key field from the EF model and doing some reflection on the entity, but that probably slows down the process remarkably.

Note that an Attached persisted object is ignored by this method: it is assumed that it will be saved by the context it already belongs to.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.