简体   繁体   English

WCF 数据服务和 Upserts

[英]WCF Data Services and Upserts

I have a WCF Data Services with an entity named Contract.我有一个名为 Contract 的实体的 WCF 数据服务。

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.有时我会得到一个 updateException ,因为当链接已经存在时,我试图在合同和报价之间添加一个链接。

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?还是 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我自己问了一个类似的问题 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().您要么需要检查现有关系(然后取决于您的效率如何),要么您可以将 Upsert 功能放入存储过程(例如 sp_UpsertQuote(contractId, quoteId) 并调用它而不是使用 SaveChanges ()。

If you have SQL Server 2008 R2 then I would recommend you create a SQL server stored procedure that utilizes Merge .如果您有 SQL Server 2008 R2 ,那么我建议您创建一个使用Merge的 SQL 服务器存储过程。

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.这样做的好处是您不需要为了确定是否需要创建或更新而向数据库发出多个请求。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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