问题
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:
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.
回答2:
I just create an MERGE statement in a stored procedure and then map the function import to return nothing.
来源:https://stackoverflow.com/questions/3777652/how-to-do-a-server-side-insert-update-upsert-from-silverlight-ria-services