c# - LINQ to Entities 不支持指定的类型成员 'Items'

标签 c# asp.net-mvc linq entity-framework linq-to-entities

我是第一次使用代码优先方法创建我的项目,在使用数据库优先方法创建我的项目时,我从未见过弹出此错误。

我知道这里有很多这样的错误,但我已经检查过它们,似乎我需要有人向我解释我的特定示例中的错误,以便我更好地理解它。

错误

The specified type member 'Items' is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties are supported.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.NotSupportedException: The specified type member 'Items' is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties are supported.

错误原因

public dynamic List()
{
    var categories = db.Categories.OrderByDescending(x => x.CreatedDateTime).Select(x => new
    {
        ID = x.ID,
        Name = x.Name,
        RootCategoryName = x.RootCategory.Name,
        ItemCount = x.Items.Count() // This line
    });

    return Json(categories, JsonRequestBehavior.AllowGet);
}

项目模型

public class Item
{
    public int ID { get; set; }

    public int CategoryID { get; set; } // Seems like here I've done everything correctly
    public Category Category { get; set; } // Seems like here I've done everything correctly

    [Required]
    public string Name { get; set; }
    public string Info { get; set; }

    public bool? IsAccessory { get; set; }
    public int? RootItemID { get; set; }
    public Item RootItem { get; set; }
}

类别模型

public class Category
{
    public int ID { get; set; }

    public int? RootCategoryID { get; set; }
    public Category RootCategory { get; set; }

    [Required]
    public string Name { get; set; }
    public string Info { get; set; }

    public IQueryable<Item> Items { get; set; } // Here also it seems that I've done relations correctly

    public DateTime CreatedDateTime { get; set; }
    public DateTime ModifiedDateTime { get; set; }
}

乍一看,似乎不可能使用代码优先调用类似 Category.Items.Count()Item.Category.Name 之类的东西,但我认为我在代码上做错了,因为它应该是可能的。请帮忙,我应该怎么做才能使这项工作正常进行?

最佳答案

Category.Items应该是 ICollection<Item> 类型而不是 IQueryable<Item>

关于c# - LINQ to Entities 不支持指定的类型成员 'Items',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12654149/

相关文章:

c# - 使用 C# 从 XML 中删除没有属性的空元素?

c# - 将 Auth0 与 Umbraco 7 集成以进行成员身份验证

c# - 如何建模这个实体

c# - IIS 工作线程与 Web 应用程序线程

asp.net-mvc - 如何隐藏 Bootstrap 表中的列?

c# - 如何使用先前输入的参数重新加载页面?

c# - 看不到 FirstOrDefault

c# - 正则表达式匹配后如何选择n个字符

asp.net-mvc - 如何检查 Controller 中是否已经存在用户?

c# - 将 Func 传递给 Where 将返回类型从 IQueryable 更改为 IEnumerable