Archive for the ‘LINQ’ Category

Using LINQ to validate StrongTyped Dataset

December 8, 2008 2 comments
I was working on asp:CustomValidator within a GridView  to notify user  in case of a duplicate selection.

The validation LINQ code I have used in the beginning  is very straight forward for StrongTyped Dataset:

   1: CrisisRecordDS.CrisisChargesViewDataTable dt = this.CrisisRecord.CrisisChargesView;
   2: int chargeId = Int32.Parse(args.Value);
   3: int count = dt.Where(ch => ch.Charge_ID == chargeId).Count();
   4: args.IsValid = count == 0;

However, this code failed to evaluate my Dataset.

The reason for that the Charge_ID for the last record is not yet set  at this moment of the execution. Dataset is strongly typed, Linq calls the ch.Charge_ID to compare with chargeId and fails because of InvalidCastException.


After couple tries, I decided to use "untyped" approach and came up with this solution

   1: int chargeId = Int32.Parse(args.Value); 
   2: var count = (from ch in   this.CrisisRecord.CrisisChargesView.AsEnumerable()
   3:      where ch.Field<object>("Charge_ID") != null && ch.Field<int>("Charge_ID") == chargeId
   4:      select ch).Count();
   6:  args.IsValid = count == 0;

The appealing fact here that I could apply different generics types for the same Field : ch.Field<object>("Charge_ID") != null to check for null and ch.Field<int>("Charge_ID") == chargeId to compare.

Categories: LINQ