WCF 数据服务和更新插入
我有一个 WCF 数据服务,其实体名为 Contract。
合约和报价之间存在多对多关系: ( * ) Contract <---->; ( * ) 报价
我有一种方法可以添加/删除合同和报价之间的链接。
有时我会收到 updateException ,因为我试图在合同和报价之间添加链接,而该链接已经存在。
我想编写一个查询,仅当链接尚不存在时才添加链接,而不需要在数据库中查询合同和报价之间的现有链接。
有没有办法使用表达式树来做到这一点?或者林克?
目前,我这样做:
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 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();
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我自己对 Silverlight 提出了类似的问题 如何从 Silverlight RIA 服务进行服务器端插入/更新 (Upsert)
您要么需要检查现有关系(然后就取决于您的效率如何),或者您可以把你的将功能更新到存储过程(例如 sp_UpsertQuote(contractId, quoteId))并调用它,而不是使用 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().
如果您有 SQL Server 2008 R2,那么我建议您创建一个利用 合并。
如果你不这样做,那么我仍然会编写一个存储过程来更新插入。
这样做的好处是,您不需要仅仅为了确定是否需要创建或更新而向数据库发出多个请求。
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.