Home > LINQ > Using LINQ to validate StrongTyped Dataset

Using LINQ to validate StrongTyped Dataset

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
  1. June 23, 2013 at 5:29 pm

    Good way of describing, and good piece of writing to obtain information on the topic of my
    presentation topic, which i am going to present in university.

  2. July 26, 2013 at 2:47 am

    Thanks for one’s marvelous posting! I truly enjoyed reading it, you are a great author. I will ensure that I bookmark your blog and will often come back very soon. I want to encourage that you continue your great posts, have a nice afternoon!

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: