Linq-to-SQL连接查询的问题

时间:2011-07-04 16:08:57

标签: sql linq-to-sql join

var grid = new System.Web.UI.WebControls.GridView();
        grid.DataSource = from booking in bookings
                         join f in getallAttendees on booking.UserID equals f.UserID into fg
                         from fgi in fg.DefaultIfEmpty() //Where(f => f.EventID == booking.EventID)
                          where
                              booking.EventID == id

                          select new
                          {
                              EventID = booking.EventID,
                               UserID = booking.UserID,
                              TrackName = booking.Name,
                              BookingStatus = booking.StatusID,
                               AttendeeName = booking.FirstName,
                             // name = account.FirstName,
                              AmountPaid = booking.Cost,
                              AttendeeAddress = booking.DeliveryAdd1,
                              City = booking.DeliveryCity,
                               Postcode = booking.Postcode,
                              Date = booking.DateAdded,
                              product = fgi == null ? null : fgi.productPurchased
                         };

Booking表格设计:

ID, EventID, UserID, BookingStatus, AmountPaid, AttendeeAddress, City, Date

Product表格设计:

ID, EventID, SecondDriver, Apples, Bananas, SecondItem

预订和产品表之间的关联是多对多的,外键是UserID

上面的Linq-to-SQL查询仅返回booking.UserID equals att.UserID用户的数据,我想要的是返回该特定事件的所有用户,如果他们已经购买了其他填充null在那些专栏中。

任何可能的解决方案或示例都将受到高度赞赏。

1 个答案:

答案 0 :(得分:1)

我认为你正在寻找一个与左连接相当的东西。您可以使用DefaultIfEmpty()扩展方法完成此操作。修改您的连接语句并添加另一个from in,如下所示:

join at in getallAttendees on booking.UserID equals at.UserID into attg
from att in attg

在您的select语句中,您可以使用三元运算符? :,如下所示:

SecondItem = att == null ? null : att.SecondItem,

修改

如果您希望将bookingsgetallAttendees {IQ}一起加入,则getallAttendees.ToList()bookings.ToList() IQueryable需要来自相同的上下文。

否则您需要使用{{1}}和{{1}}