【问题标题】:EF Lambda How to make projection for GroupJoinEF Lambda 如何为 GroupJoin 进行投影
【发布时间】:2019-04-13 12:21:19
【问题描述】:

我正在尝试查询 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; }

}

【问题讨论】:

    标签: entity-framework linq lambda


    【解决方案1】:

    您无需明确使用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()`
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-29
      • 2012-04-24
      • 2020-05-25
      • 2019-07-21
      相关资源
      最近更新 更多