3

Can someone suggest the best exception handling mechanism in LINQ? Suppose I have the following function:

public List<test_dataRange> GetDataRange()
{
    testDataContext = new ParentDataContext(conn);
    List< test_dataRange > dataRange = (from pp in testDataContext. test_dataRanges
                                                    select pp).ToList();

    return dataRange;
}

What are the best exception handling mechanisms in LINQ that can be applied here? Also What are the best exception handling mechanisms for those functions with Transaction, For eg:

 public void UpdateQAProperty(Data_QAProperty qaProperty)
        {
            parentDataContext = new ParentDataContext(conn);
            DbTransaction dbTransaction = null;
            parentDataContext.Connection.Open();
            dbTransaction = masterDataContext.Connection.BeginTransaction();
            parentDataContext.Transaction = dbTransaction;
            var property = (from y in parentDataContext. QAProperties
                            where y.Id == qaProperty.Id
                            select y).FirstOrDefault();
            property.Height = qaProperty.Height;
            property.Caption = qaProperty.Caption;
            property.Width = qaProperty.Width;
            property.Length= qaProperty.Length;

            parentDataContext.SubmitChanges();
            dbTransaction.Commit();

        }
Habib
  • 219,104
  • 29
  • 407
  • 436
Bisileesh
  • 1,982
  • 2
  • 19
  • 29

1 Answers1

1

I think your linq query runs just fine.

var property = (from y in parentDataContext. QAProperties
                            where y.Id == qaProperty.Id
                            select y).FirstOrDefault();

However, FirstOrDefault will return the first object meeting the criteria or null if none exist.

Despite the possibility of property being null, you continue with your setters

 property.Height = qaProperty.Height;
 property.Caption = qaProperty.Caption;
 property.Width = qaProperty.Width;
 property.Length= qaProperty.Length;

This is going to throw an exception because property is null.

I can't tell from your post whether or not that is acceptable. (Is qaProperty.Id null? Is it zero? Why wasn't the expected property found?)

You have a few alternatives:

  1. When property is null, create a new one and add that in your transaction
  2. Gracefully escape when property is null and notify the user the property was not found

The rollback is unnecessary. Entity Framework failed before parentDataContext.SubmitChanges(); was ever reached. If SubmitChanges was successfully called, all of the records in that unit of work would have been updated.

As for the using block, you can stick a try-catch in there.

Josh C.
  • 4,303
  • 5
  • 30
  • 51