2

Why this is giving me the parameterless contructor error?

ObservableCollection<ArchivioErogazioniForList> tempHP = new ObservableCollection<ArchivioErogazioniForList>();

var erogazioniFiltrate = from r in MainWindow.dbContext.ArchivioErogazioni
                             where termToFind.Contains(r.IDTER.Value) && r.DATA_EROG >= test
                             select r;
tempHP = new ObservableCollection<ArchivioErogazioniForList>(erogazioniFiltrate.Where(x => x.DATA_EROG >= test).Select(x => new ArchivioErogazioniForList(x)));

while this is working??

private ObservableCollection<ArchivioErogazioniForList> p_ListaMonitorErogazioni2;
public ObservableCollection<ArchivioErogazioniForList> ListaMonitorErogazioni2
{
    get { return p_ListaMonitorErogazioni2; }
    set { 
        p_ListaMonitorErogazioni2 = value;
        base.RaisePropertiesChanged("ListaMonitorErogazioni2"); 
    }
}

allRecords = (from r in MainWindow.dbContext.ArchivioErogazioni select r).ToList();

ListaMonitorErogazioni2 = new ObservableCollection<ArchivioErogazioniForList>(allRecords.Where(x => x.DATA_EROG >= startDate && x.DATA_EROG <= endDate).Select(x => new ArchivioErogazioniForList(x)));

Where are the differences? The first snippet give me the error "System.NotSupportedException: Only parameterless constructors and initializers are supported in LINQ to Entities."

2 Answers 2

9

The error says it all. In LINQ to Objects, constructors can be called without a problem. But in LINQ to Entities, cannot do that. The framework works by first creating the instance itself (eg. it needs parameterless constructor) and then sets the individual properties. Simplest way to solve this is to call AsEnumerable() before calling the select. That will materialize the data so the constructor is called via LINQ to Objects instead of being handled by Entity Framework. Like this:

erogazioniFiltrate.Where(x => x.DATA_EROG >= test).AsEnumerable().Select(x => new ArchivioErogazioniForList(x))
Sign up to request clarification or add additional context in comments.

Comments

1

The first sample uses IQueryable<T> as a source sequence for the ObservableCollection<T>.
Since it is a LINQ to Entities query, there are some limitations (using of parameterless ctor or object initializer are some of them).

The second sample first materializes IQueryable<T> via call of ToList() method. After ToList(), query results are materialized at client side, and your code works with IEnumerable<T> and LINQ to Objects, which hasn't such limitations, like LINQ to Entities does. Hence, you may call non-default ctor.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.