我是第一次使用代码优先方法创建我的项目,在使用数据库优先方法创建我的项目时,我从未见过弹出此错误。
我知道这里有很多这样的错误,但我已经检查过它们,似乎我需要有人向我解释我的特定示例中的错误,以便我更好地理解它。
错误
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/