JTunney
JTunney

Reputation: 904

An expression tree may not contain a call or invocation that uses option arguments in C# Linq

I am trying to do a case statement for one of the properties when selecting an anonymous type in the first part and then convert it to a list of my return type (retList). In the retList part at the bottom when I set QuarterName = p.QuarterName I get the following error on the DatePart functions from the section above:

An expression tree may not contain a call or invocation that uses optional arguments

public static IEnumerable<Product> GetProducts(int categoryId)
{
    using (var context = new DbContext())
    {
    var pList = (from p in context.Products
             where (p.CategoryId == proformaId)
             select new 
             {
                 Id = p.Id,
                 ProductName = p.ProductName,
                 QuarterName = pa.Quarter != "ExtraQuarter" ? "Q" + DateAndTime.DatePart(DateInterval.Quarter, p.PurchaseDate) + 
                                               "-" + DateAndTime.DatePart(DateInterval.Year, p.PurchaseDate) : 
                                               "<b><i>" + p.Quarter + "</i></b>"

             }).ToList();

      var retList = from p in pList
                    select new ProformaAssumption()
                    {
                        Id = pa.Id,
                        ProductName = p.ProformaId,
                        QuarterName = p.QuarterName
                    };

      return retList;
    }

Upvotes: 4

Views: 5538

Answers (1)

StriplingWarrior
StriplingWarrior

Reputation: 156614

The DatePart methods have additional, optional parameters. C# doesn't allow Expression Trees to leverage the optional parameters, so you'll need to provide the whole parameter list to each of these method calls.

According to the documentation, FirstDayOfWeek.Sunday and FirstWeekOfYear.Jan1 are the values that would be used if you didn't provide a value for the optional parameters.

QuarterName = pa.Quarter != "ExtraQuarter" 
    ? "Q" +
        DateAndTime.DatePart(DateInterval.Quarter, p.PurchaseDate,
            FirstDayOfWeek.Sunday, FirstWeekOfYear.Jan1) + 
        "-" + DateAndTime.DatePart(DateInterval.Year, p.PurchaseDate,
        FirstDayOfWeek.Sunday, FirstWeekOfYear.Jan1) 
    : "<b><i>" + p.Quarter + "</i></b>"

Upvotes: 3

Related Questions