Check if I have already inserted a particular record
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 conta开发者_运维问答in 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 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
}
Try this:
!context.PaymentMethods.Where(paymentMethod => paymentMethod.PaymentMethodID == iPaymentMethod.PaymentMethodID).Count() = 0
精彩评论