jmasterx
jmasterx

Reputation: 54183

Finding out if an update succeeded with LINQ SQL?

I found this code from a tutorial:

Product bev1 = beverages.ElementAtOrDefault(10);
if (bev1 != null)
{
    Console.WriteLine("The price of {0} is {1}. Update to 20.0", 
                      bev1.ProductName, bev1.UnitPrice);
    bev1.UnitPrice = (decimal)20.0;
}
// submit the change to database
db.SubmitChanges();

How do we know if the update was successful?

Upvotes: 2

Views: 758

Answers (3)

D Stanley
D Stanley

Reputation: 152634

It depends on what you mean by "successful". If by successful you mean "no error occurred" then the lack of an exception will tell you that. If you mean "the data updated in the database as I expected" then you'll need to either query the database off-line or create another context and run a query through it to verify the changes happened.

You could write code that doesn't generate an exception but doesn't update the database the way you'd expect it to.

Upvotes: 0

Pranay Rana
Pranay Rana

Reputation: 176956

one way to know is No exception was thrown.

second way to make sure is use of GetChangeSet method to get the modified objects tracked by the data context.

Example form msdn

Northwnd db = new Northwnd(@"c:\northwnd.mdf");

var custQuery =
    from cust in db.Customers
    where cust.City == "London" 
    select cust;

foreach (Customer custObj in custQuery)
{
    Console.WriteLine("CustomerID: {0}", custObj.CustomerID);
    Console.WriteLine("\tOriginal value: {0}", custObj.City);
    custObj.City = "Paris";
    Console.WriteLine("\tUpdated value: {0}", custObj.City);
}

//get object modified 
ChangeSet cs = db.GetChangeSet();
Console.Write("Total changes: {0}", cs);
// Freeze the console window.
Console.ReadLine();

db.SubmitChanges();

Upvotes: 2

Servy
Servy

Reputation: 203841

If the update is not successful an exception will be thrown. If no exception is thrown, it was successful.

Upvotes: 1

Related Questions