WCF and Upserts Data Services

I have a WCF data service with an entity named Contract.

between Contracts and Quotes, there are many, many: (*) Contract <----> (*) Quotes

I have a method that adds / removes links between contracts and quotes.

and sometimes I get an updateException because I try to add a link between Contract and Quote when the link already exists.

I want to write a query that adds a link only if the link does not exist yet, without having to query the database for existing links between my contract and quotation marks.

Is there a way to do this using expression trees? or linq?

At the moment I am doing this:

void ModifyContract(Contract ctr) { var contractInDb = (from c in service.Contracts.Expand("Quotes") where c.Id == ctr.Id).Single(); foreach(q in ctr.Quotes) { if( ! contractInDb.Quotes.Contains(q)) { service.AddLink(ctr,"Quotes", q); } } service.SaveChanges(); } 
+4
source share
2 answers

I asked myself a similar question for Silverlight How to make a tab / update (Upsert) on the server side from RIA Silverlight services

You need to either check the existing relationship (then it’s just not how efficient you can do it), or you can add Upsert functionality to the stored procedure (for example, sp_UpsertQuote (contractId, quoteId) and call it instead of using SaveChanges ().

+2
source

If you have SQL Server 2008 R2 , I would recommend that you create a SQL Server stored procedure that uses Merge .

If you do not, I will still write a stored procedure for the update.

The advantage of this is that you do not need to make multiple database queries just to find out if you need to create or update.

+2
source

All Articles