tags:

views:

45

answers:

2

I am going through a massive list of business objects and inserting them into the database using Linq-to-Sql.

Some of the business objects contain a payment method record (cheques, credit card etc..)

When it comes to adding a payment method, I want to check to ensure I havent already added it, cos otherwise it will rant at me when I come to Submit my changes.

if ( !context.PaymentMethods.Any ( paymentMethod => paymentMethod.PaymentMethodID == iPaymentMethod.PaymentMethodID ) )
{
    PaymentMethod method = new PaymentMethod ();
    method.PaymentMethodID = iPaymentMethod.PaymentMethodID;

    // etc...

    context.PaymentMethods.InsertOnSubmit ( method );
 }

This doesnt work, I presume because Any is checking the database and not the list of objects I am about to Insert on Submit.

I know I can maintain my own list to check if the records have already been added, but to save a lot of hassle, I was just wondering if there was a tidy, Linq way to do this? Any way to check context.PaymentMethods to see if it has been added?

A: 

Try this:

!context.PaymentMethods.Where(paymentMethod => paymentMethod.PaymentMethodID == iPaymentMethod.PaymentMethodID).Count() = 0
Randy Minder
Nope, same thing. Presumeably this is checking if it is in the database, not in my submit list.
Mongus Pong
+2  A: 

A possible solution would be to check the ChangeSet of the Context:

Func<PaymentMethod,bool> f = 
     paymentMethod => paymentMethod.PaymentMethodID == iPaymentMethod.PaymentMethodID;

if (!context.PaymentMethods.Any(f) && 
    !context.GetChangeSet().Inserts.OfType<PaymentMethod>().Any(f))
{
   // Submit
}
bruno conde
Sweet as sugar pie!! :o)
Mongus Pong