1

I'm new to linq to sql and I have some complex SQL query.

My SQL Server query does this shortly: I have 2 tables, product (a) and productorder (b). Product has amount and a second amount which warns the customer how many items still in progress.

In "a" we have 10 papers if we order 5. Then table a second amount value is 5. If we order more : 5 = 5 + more

So I write my T-SQL here. I want a linq to sql

UPDATE a 
SET a.secondamount = a.secondamount + b.orderedamount 
INNER JOIN b ON a.productid == b.productid 
WHERE b.status = false ;
2
  • You Write already a SQL Query. Do You want to translate this to LINQ? Commented Aug 23, 2016 at 10:28
  • Yes , this code snippet what i used in my old program. Right now i have to replace every sqlcommand/reader etc to linq to sql. I almost replaced everything i stucked with this one. Commented Aug 23, 2016 at 10:38

1 Answer 1

1

Linq is not used for updating but for querying. You can use linq to find all the records you want to update and prepare the data but then the update itself should happen separately.

var result = from itemA in a
             join itemB in b on itemA.productId equals itemB.productId
             where itemB.Status == false
             select new { itemA, itemB.orderedamount };

foreach(var item in result)
{
    //do update using item.itemA.secondAmount + item.orderedamount
}
Sign up to request clarification or add additional context in comments.

9 Comments

Gilad, sorry, tried to make your query compilable and introduced another silly mistake.
I meant I broke your answer with my first edit, so I apologize for that.
@IvanStoev - ahh ok ya got it. The equals was just a silly mistake :) haha. About the join compared to the where - I know the join is the correct one in terms of how the original sql but what will happen if that join yields more than one record?.. that is why I changed it to the Any
Well, specifically in this case I was not thinking for performance or cardinality, but only that you need itemB inside the select :-)
@IvanStoev - och of course haha stupid me. I did it with the join initially and then changed without checking haha :) thanks for the edit
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.