EF Lambda如何为GroupJoin进行投影

时间:2019-04-13 12:21:20

标签: entity-framework linq lambda

我正在尝试查询EF模型。 (GameBank和GameCouponBank)如何为左外部联接(GoupJoin)进行投影?

我可以为优惠券进行投影吗?

这是我的查询

var gameBankResult = context.GameBanks.GroupJoin(context.GameCouponBanks, g => g.GameBankID, gc => gc.GameBankID,
                (g,gc) => new {
                    g.quantity,
                    g.currency,
                    g.initiationResultCode,
                    g.productCode,
                    g.productDescription,
                    g.referenceId,
                    g.responseDateTime,
                    g.unitPrice,
                    g.totalPrice,
                    Coupons = gc

                 })
                .Where(g => g.productCode == initiate.productCode)
                .Select(s => s);

以下是模型:

public class GameBank
{
    public int GameBankID { get; set; }
    public string referenceId { get; set; }
    public string productCode { get; set; }
    public int quantity { get; set; }
    public string version { get; set; }
    public DateTime? requestDateTime { get; set; } = DateTime.Now;
    public int? customerID { get; set; }
    public string password { get; set; }
    public DateTime? responseDateTime { get; set; } = DateTime.Now;
    public string initiationResultCode { get; set; }
    public string companyToken { get; set; }
    public int used { get; set; }
    public string productDescription { get; set; }
    public string currency { get; set; }
    public double unitPrice { get; set; }
    public double totalPrice { get; set; }
    public virtual List<GameCouponBank> coupons { get; set; }
}

public class GameCouponBank
{
    public int Id { get; set; }
    public int GameBankID { get; set; }
    public DateTime? expiryDate { get; set; }
    public string Serial { get; set; }
    public string Pin { get; set; }

}

1 个答案:

答案 0 :(得分:0)

您不需要显式使用GroupJoin。您可以按照以下方式简单地设计查询:

var gameBankResult = context.GameBanks.Where(g => g.productCode == initiate.productCode)
                 .Select(g => new {
                    g.quantity,
                    g.currency,
                    g.initiationResultCode,
                    g.productCode,
                    g.productDescription,
                    g.referenceId,
                    g.responseDateTime,
                    g.unitPrice,
                    g.totalPrice,
                    Coupons = g.coupons.Select(c => new {c.Id, c.GameBankID,...}).ToList() //<-- Here is the projection for coupons
                 }).FirstOrDefault(); // I assume you are returning single entity, if not then use `.ToList()` instead of `.FirstOrDefault()`
相关问题