【问题标题】:Cannot initialize type "MyDataCollection" with a collection initializer because it does not implement 'System.Collections.IEnumerable'无法使用集合初始化程序初始化类型“MyDataCollection”,因为它没有实现“System.Collections.IEnumerable”
【发布时间】:2014-08-06 10:43:37
【问题描述】:

大家好,我正面临上述错误。 我只想使用 edmx 从数据库中检索两列。 运行时出现以下错误:

"不能用集合初始化器初始化类型,因为它确实 不实现 ienumerable。”

using (DBEntities context = new DBEntities())
{
    IList<myData> objData = null;
    objData = context.EDatas
        .Where(entity => entity.Status == 0 && entity.Id == Id)
        .Select(entity => new myData
        { 
            entity.ID, 
            entity.Key                          
        }).ToList();                  
}

【问题讨论】:

    标签: c# entity-framework edmx


    【解决方案1】:

    代替

    .Select(entity => new myData
    { 
        entity.ID, 
        entity.Key                          
    })
    

    您需要使用myData的正确属性名称:

    .Select(entity => new myData
    { 
        ID = entity.ID, 
        Key = entity.Key                          
    })
    

    否则编译器会假定您要填充集合。

    【讨论】:

    • 我已经尝试过了,它给出了以下错误“无法在 LINQ to Entities 查询中构造实体或复杂类型 'DBModel.myData'”
    • @SantoshSingh:我对L2E不熟悉,这是原因和解决方案:stackoverflow.com/questions/5325797/…
    【解决方案2】:

    您没有创建匿名类型,编译器认为您正在使用集合初始值设定项语法创建一个集合。您应该像这样使用属性名称并设置值:

    .Select(entity => new myData
                      { 
                           Id = entity.ID, 
                           Key = entity.Key                          
                      }).ToList();  
    

    【讨论】:

    • 我已经尝试过了,它给出了以下错误“无法在 LINQ to Entities 查询中构造实体或复杂类型 'DBModel.myData'”
    • @SantoshSingh 在 Where 之后添加 AsEnumerable。
    猜你喜欢
    • 1970-01-01
    • 2014-04-21
    • 2017-08-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多