views:

166

answers:

1

While RIA services seems very good for table operations & queries, I am stuck on one traditional update situation. The UPSERT (Update if exists, else Insert new):

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

Second: I do not want to query the database from client-side, to see if the record exists. I just want to call an "UpsertData" method on RIA services and have the add or update occur server-side only.

I have tried many options, the closest I got used an [Update(UsingCustomMethod = true)] method, passing a newly created (therefore detached) Entity. When call the method with my object I get: "A custom method cannot be invoked on a Detached Entity."

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

+1  A: 

OK, I have a solution. I'm not sure if this is the correct way to do it, so will await confirmation from your good selves.

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

Client Side code to do Upsert:

  • Create a domain context
  • Create a new entry, that might already exist
  • Add the new item to the domain context (to appropriate table)
  • Submit the changes (effectively request a 1 record insert).

Server Side code:

  • Replace the existing InsertTypeX( TypeX object ) method.
  • Have the InsertTypeX method check for an existing record.
  • If an existing record exists, update the required fields on that record.
  • If a record does not exist, use AddObject to add the object to the EF table.

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

Enough already
That's exactly the approach I would recommend. The code generated by the Domain Service Wizard is meant to be a starting place for you to customize with logic specific to your application.
Kyle McClellan
@Kyle McClellan: Thanks for confirming. The more I get into this the clearer it gets (just got to get out of the initial fog first :))
Enough already