0

I have a payment system as shown below. The payment can be made through multiple gift coupons. The gift coupons are issued along with a purchase. The customer can make use of this gift coupon for future purchase. When a Payment is made through gift coupon, the UsedForPaymentID column in GiftCoupon table will be updated with that PaymentID (for the giftcoupon ID). PaymentID is a foreign key in GiftCoupon table.

I need to write a method:

public DateTime GetPaymentDate(int GiftCouponID) 

This method will find the date on which a payment is made using the gift coupon.

For achieving this, I can do the following steps

  1. Find the GiftCoupon object using GiftCouponID (from GiftCoupon repository)
  2. Find the PaymentID from the GiftCoupon object. Store it in @PID variable
  3. Using the @PID variable find the Payment object (from Payment repository)
  4. Find the PaymentDate from Payment object

Is there a easier/efficient way of doing this in LINQ to SQL?

enter image description here

2 Answers 2

2

You could try something like this.

public DateTime GetPaymentDate(int GiftCouponID) {
    using(var db = new YourDataContext()) // Create a datacontext
    {

        GiftCoupon gc = db.GiftCouple.SingleOrDefault(g=>g.GiftCouponID == GiftCouponID)
        if(gc != null)
            return gc.Payment.PaymentDate;
        else 
            throw new Exception("No such GiftCouponID");
    }
}

I've added basic error checking, you may need more/less dependant on how your system works. Obviously you also need to change the name of the DataContext.

Assuming all of your relationships are setup correctly this (or something similar) should work for you.

1
  • As Amiram (below) has coded, you might also want to cater for the event that your GitfCouponID provided has not yet been used. I.e. check for a null field.
    – KingCronus
    Jul 12, 2012 at 9:47
1
var c = context.GiftCoupons.FirstOrDefault(gc => gc.GiftCouponID == GiftCouponID);
if (c != null && c.Payment != null)
return c.Payment.PaymentDate
1
  • 1
    I'm not sure that this is correct, why would UsedForPaymentID ever equal GiftCouponID?
    – KingCronus
    Jul 12, 2012 at 9:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.