简体   繁体   中英

Call Function In LinQ Query

I want to sum price for all products that is in list. I called a funtion in linQ query.

Total = t0.TbOfferProducts.Sum(x => Customs.CalculateCurrency(x.TbOffer.Price))

But it didnt recognize my function I wrote another function for linQ, then I called it. But linQ dont recognize my function.

Error: LINQ to Entities does not recognize the method 'Double Cal_Price(Int32)' method, and this method cannot be translated into a store expression.

I try other versions but none of them didnt work.Help me please.

myList = 
    (from t0 in DB.TbProducts
    where t0.BoActive == true && t0.BoSoftDeleted == false
    let price = Cal_Price(t0.InProductId)
    select new ProductActivityInfo
    {

        ID = t0.InProductId,
        Name = t0.StProductName,
        Code = t0.StProductCode,
        Total = price
    })
public double Cal_Price(int productId)
{
    double  total = 0;
    using (MyEntityContext DB = new MyEntityContext())
    {
        var list = DB.TbOfferProducts.Where(x => x.InProductId == productId);

        foreach (var item in list)
        {
            total += Customs.CalculateCurrency(item.TbOffer.Price);
        }
    }

    return total;
}

EF Core is tryng to build SQL but fails when found custom compiled method in query. Correct Total on the client side:

// calculate sum by grouping
var offerPrices =
    from op in DB.TbOfferProducts
    group op.TbOffer.Price by x.InProductId
    select new 
    {
        ProductId = g.Key,
        RawPrice = g.Sum()
    };

var result = 
    (from t0 in DB.TbProducts
    join op in offerPrices on t0.InProductId equals op.ProductId
    where t0.BoActive == true && t0.BoSoftDeleted == false
    select new ProductActivityInfo
    {

        ID = t0.InProductId,
        Name = t0.StProductName,
        Code = t0.StProductCode,
        Total = op.RawPrice
    })
    .ToList();

// correct Total on the client side
result.ForEach(x => x.Total = Customs.CalculateCurrency(x.Total));  

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