[c#]LINQ/实体框架︰ 无参数构造函数问题

发布时间: 2017/2/28 22:39:00
注意事项: 本文中文内容可能为机器翻译,如要查看英文原文请点击上面连接.

为什么这给我的无参数构造函数错误?

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)));

虽然这工作??

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)));

区别在哪里?第一段给我错误"System.NotSupportedException︰ 仅无参数构造函数初始值设定项支持和在 LINQ 到实体."

解决方法 1:

该错误说明了一切。在 LINQ 到对象中,可以调用构造函数,没有问题。但在 LINQ 中的实体,不能这样做。框架的工作原理是首先创建该实例本身 (如.它需要无参数构造函数),然后设置的各个属性。为了解决这个问题的最简单方法是调用 AsEnumerable() 之前调用选择。这将实现数据,所以调用了构造函数,而不是由实体框架通过 LINQ 到对象。喜欢这个:

erogazioniFiltrate.Where(x => x.DATA_EROG >= test).AsEnumerable().Select(x => new ArchivioErogazioniForList(x))
赞助商