简体   繁体   中英

How can I refresh my local database from a web service when an item isn't found?

The project I am working on involves a database and a web service for the source of data. This question, and I have several, is based on the idea that if I enter in a product number in textBox1 , I want to see if the number is already in the database, if not I want to have it run my written code that goes to a web service and grabs the data and then updates the database.

  1. What code should I use to check if the Product_ID is null or empty

  2. What code do I need to write so that if the Product_ID is null or empty it will invoke the code I have already written that grabs data from a web service?

My linq code is:

Test_Data_ClassDataContext db = new Test_Data_ClassDataContext();
            var q = from p in db.Product_Masters
                    where p.Product_ID.Equals(textBox1.Text)
                    select p;

stealing from others ideas I am trying to test for null if null run the web service code if not null send it to datagridview for display.

If (q == null)
{
    Somehow call the other code so it takes textBox1 and get the data from the service
}

else
{
    dataGridView1.DataSource = q;
}

Background: I am a newbie to c#, once upon a time I played with vb6 and so to me c# is not only like learning a new language but also learning to walk again, not to mention I was never a good vb6 programmer.

q will never be null.

The value of a query expression is an object representing the query . It is not the results of the query .

If what you want to know is "does this query have any results" then say "q.Any()".

Because linq to sql uses defered execution until GetEnumerator() is called you need to fist invoke your query.

var result = q.ToList();

if (result.Count == 0)
{
  //Somehow call the other code so it takes textBox1 and get the data from the service
}
else
{
  dataGridView1.DataSource = result;
}

Now that you have invoked the query you can simply check if there are results, if not you can simply call your webservice.

What you also want to know is: "how do i call a webservice?".

This is a topic onto itself: In VS this is made easy by adding the service reference (either a Web Service Reference for ASMX services or a Service Reference for a WCF service).

I suggest Googling for info on either subjects and how to tell them apart.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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