WCF Data Services and Upserts
I have a WCF Data Services with an entity named Contract.
there is a many to many between Contracts and Quotes : ( * ) Contract <----> ( * ) Quotes
I have a method that adds/remove links between contracts and quotes.
and sometimes I get an updateException because I'm trying to add a link between a Contract and a Quote when the link is already existent.
I want to write a query that adds a link only if the link doesn't exist yet without needing to query the database for the existing links between my contract and quotes.
Is there a way of doing that using Expression Trees ? or Linq ?
At the moment, I do 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))
开发者_JAVA百科 {
service.AddLink(ctr,"Quotes", q);
}
}
service.SaveChanges();
}
I asked a similar question myself for Silverlight How to do a server-side Insert/Update (Upsert) from Silverlight RIA services
You either need to check for an existing relationship (then it is just down to how efficient you can make it), or you can put your Upsert functionality into a stored procedure (e.g. sp_UpsertQuote(contractId, quoteId) and call that instead of using SaveChanges().
If you have SQL Server 2008 R2 then I would recommend you create a SQL server stored procedure that utilizes Merge.
If you don't then I would still write a stored procedure to upsert.
The benefit of this is that you don't need to make multiple requests to the Database just to figure out if you need to create or update.
精彩评论