0

I'm new using linq and I have a question: I need to create a query to use later with SqlCommand that is like this:

string query = string.Format(@"
UPDATE dtLct SET
    bLctVer = 1
WHERE pLct IN (@value1, @value2, @value3)
", value1, value2, value3);

but I wish the values retrieve from a List<int> I'm able to compose a query ciclyng the values, but I wish use linq.. it's possible?

thanks

1 Answer 1

1

Yes it is possible like below:

string values = String.Join(",",list.ToArray());

where list is the list of your integers.

Then your query should change to the following one:

string query = "UPDATE dtLct " +
               "SET bLctVer = 1 " +
               "WHERE pLct IN ("+values+")";

If you don't like this approach and you would like pure LINQ, then you could try the following one:

// Get the items that are to be updated from the database.
var items = (from b in db.bLctVer
            where list.Contains(b.pLct)
            select b);

// Iterate through the items and update tje value of bLctVer
foreach(var item in items)
    item.bLctVer=1;

// Submit the changes.
db.SubmitChanges();

Note

I have to note here that the first approach is more optimal, since you will have only one round trip to the database. Using the second approach, you make two round trips. In the first trip, you get the records that should be updated and in the second trip you update them.

Sign up to request clarification or add additional context in comments.

2 Comments

@ghiboz you welcome. I din't use linq in the above code. I just made a string of the values you are looking for and then I built the correspoding sql command (the text of the sql command).
@ghiboz please see my updated post and let me know if the second approach is what you are looking for.

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.