简体   繁体   中英

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))
         {
              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 (eg 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM