josh
josh

Reputation: 29

how to filter a sql condition in c#

i have the following table is sql

Id | transaction

15 |4785-t48er8-565

24 |4587-dsfs-89554

784|sdf487-89d5-5sd

in my program i pass in a transaction in which i first need to check if the transaction exists in the database as follows

     var entry = (await _Repository.AsQueryableAsync()).FirstOrDefault(x => x.transaction == command.transaction);
     if (entry !=null)
    {
    // do something
    }

so the above works. My question is the transaction that exists how do i check if that transaction is equal to the id i pass in

for example if i pass the following response from my api as

"transaction": "4785-t48er8-565",
"id":569 

it will then check with the above code that the transaction exists. Now as you can see in the table the transaction 4785-t48er8-565 has an id of 15 but in my response i passed in 569

how do i check if the transaction matches the id. I need to check first if it exists and then match it to the id

Upvotes: 0

Views: 154

Answers (2)

Jon Roberts
Jon Roberts

Reputation: 2282

If you need to test first for the Transaction and then separately on the Id, try:

        var entry = (await _Repository.AsQueryableAsync()).FirstOrDefault(x => x.transaction == command.transaction);
        if (entry == null)
        {
            // do no transaction stuff
        }
        else if (entry.Id == command.Id)
        {
            // do matching stuff
        }
        else
        {
            //do transaction found but Id doesn't match stuff
        }

Upvotes: 0

devcrp
devcrp

Reputation: 1348

You could just add it to the same condition you already have, like:

    var entry = (await _Repository.AsQueryableAsync()).FirstOrDefault(x => x.transaction == command.transaction);

    if (entry !=null)
    {
      if (entry.id != command.id)
      {
         // then it already exists for a different id
      }
      else
      {
         //then entry is the one that matches transaction and id
      }
    }

Then entry will be null if the condition for both properties is not met.

Upvotes: 1

Related Questions