How to Perform Server Side Insert / Update (Upsert) from RIA Silverlight Services

While RIA services are very well suited for table operations and queries, I stick to one traditional update situation. UPSERT (update, if exist, still insert new):

First: I want to add a server record if the record does not already exist, otherwise, if it already exists, I want to update one of its current field values.

Secondly: I do not want to query the database from the client side to see if the record exists. I just want to call the "UpsertData" method for RIA services and add or update the server only.

I tried many options, the closest I used the [Update (UsingCustomMethod = true)] method, passing in a newly created (hence separate) Entity. When you call a method with my object, I get: "A custom method cannot be called on a separate object."

Suggestions on the best way to do this will be appreciated :)

+1
source share
2 answers

Ok, I have a solution. I am not sure if this is the right way to do this, so you will wait for confirmation from your good ones.

Basically, I override the default Insert RIA Services method and make it an existing write check (like any other business rule check):

Client-side code to execute Upsert:

  • Creating a domain context
  • Create a new record that may already exist.
  • Add a new item to the domain context (in the corresponding table)
  • Submit changes (effectively request 1 entry).

Server Code:

  • Replace the existing InsertTypeX (TypeX object) method.
  • Ask the InsertTypeX method to check for an existing record.
  • If an existing entry exists, update the required fields in this entry.
  • If the record does not exist, use AddObject to add the object to the EF table.

It seems simple enough now, but maybe there is a better way to do this. Still open for comments and suggestions.

+2
source

I simply create a MERGE statement in the stored procedure and then map the import function so that nothing is returned.

0
source

All Articles