简体   繁体   中英

Efficient Way for Finding Reference Object in LINQ to SQL

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?

在此处输入图片说明

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.

var c = context.GiftCoupons.FirstOrDefault(gc => gc.GiftCouponID == GiftCouponID);
if (c != null && c.Payment != null)
return c.Payment.PaymentDate

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM