user576510
user576510

Reputation: 5905

how to be sure in Linq to SQL that record has been added successfully or not?

I am just learning Linq to SQL and don't know much. Kindly guide and help me.

I am adding a new record by using a SubmitChanges(); How I can be confirmed that record has been added? For example, in using stored procedures we use to send a flag back to application but how is it done in LINQ to SQL? Please guide me.

Upvotes: 2

Views: 2269

Answers (4)

Priyank
Priyank

Reputation: 10623

Check this http://msdn.microsoft.com/en-us/library/bb399378.aspx

At this point, any errors detected by the database cause the submission process to stop, and an exception is raised. All changes to the database are rolled back as if no submissions ever occurred. The DataContext still has a full recording of all changes. You can therefore try to correct the problem and call SubmitChanges again

Northwnd db = new Northwnd(@"c:\northwnd.mdf");
// Make changes here. 
try
{
    db.SubmitChanges();
}
catch (ChangeConflictException e)
{
    Console.WriteLine(e.Message);
    // Make some adjustments.
    // ...
    // Try again.
    db.SubmitChanges();
}

Upvotes: 1

Henk Holterman
Henk Holterman

Reputation: 273199

See: MSDN, How to: Submit Changes to the Database

Note that there is an overload of SubmitChanges() that will let you specidy how to handle conflicts.

Upvotes: 2

Rob
Rob

Reputation: 6871

You could do something like this;

public void Save()
{
    Northwnd db = new Northwnd(@"c:\northwnd.mdf");
    // Make changes here. 
    try
    {
        db.SubmitChanges();
    }
    catch (Exception err)
    {
        //Log error
    }
}

If no exception is thrown you can assume the data is saved correct. Though another option is something like this.

public bool Save()
{
    Northwnd db = new Northwnd(@"c:\northwnd.mdf");
    // Make changes here. 
    try
    {
        db.SubmitChanges();
        return true;
    }
    catch (Exception e)
    {
        //Log the error
        return false;
    }
}

True will be returned if save succeeds, otherwise false will be returned

Upvotes: 2

p.campbell
p.campbell

Reputation: 100567

Allow your code to flow out of your method. Only when an exception is throw has your statement not completed.

If you wanted a 'flag', you could return a bool.

public bool AddCustomer()
{
  try{
     ....
     db.SubmitChanges();
     return true;
  }
  catch(Exception e)
  {
    ...
    return false;
  }
}

Upvotes: 3

Related Questions