如何创建一个linq lambda连接查询,即使结果为null也会提取结果?

时间:2016-05-24 14:23:55

标签: c# mysql linq lambda

我有这个联接查询,可以提取个人购物车中的所有学校计划和产品:

//this pulls all items the user purchased
var poop = Context.Query<Cart>().Where(x => x.UserId == currentUserId && x.Status == "Archived")
    .Select(
        p => new
        {
            p.ItemId,
            p.TypeId,
            p.PurchaseDate
        })
//This get the media type name of the cart items
    .Join(
        Context.Query<MediaType>(),
        t => new {t.TypeId},
        m => new {TypeId = m.Id},
        (t, m) => new
        {
            t.ItemId,
            t.TypeId,
            t.PurchaseDate,
            m.TypeName
        }).OrderBy(d => d.PurchaseDate)
//Now i need specifics of the items like name, sku, etc. StartDate will be null for items that are products, but contains DateTime for items that are programs.
    .Join(
        Context.Query<ProgramProductView>(),
        e => new {e.ItemId, e.TypeId},
        prog => new {ItemId = prog.Id, prog.TypeId},
        (e, prog) => new
        {
            e.ItemId,
            e.TypeId,
            e.PurchaseDate,
            e.TypeName,
            prog.FullName,
            prog.StartDate,
            prog.Sku,
            prog.Closed
        }).OrderBy(d => d.PurchaseDate);

所以它正在崩溃,因为prog.StartDate对于产品是空的。我得到 SQL不可用错误。

有没有办法让连接允许无空字段?我只使用lambda,因为它更容易阅读和清理。

1 个答案:

答案 0 :(得分:2)

您只需要在上一个Nullable<>中使用Join属性进行匿名课程:

.Join(
    Context.Query<ProgramProductView>(),
    e => new {e.ItemId, e.TypeId},
    prog => new {ItemId = prog.Id, prog.TypeId},
    (e, prog) =>
        new
        {
            ...
            (DateTime?)prog.StartDate,
            ...
         }).OrderBy(d => d.PurchaseDate);

希望它会有所帮助。