开发者

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 proced开发者_开发百科ures we use to send a flag back to application but how is it done in LINQ to SQL? Please guide me.


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;
  }
}


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


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.


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();
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜