I’m making my project using code-first approach for the first time and I’ve never seen this error pop up when I was creating my projects using database-first approach.
I know that there is a lot of these errors here but I’ve checked them and it seems that I need someone explain to me what is wrong in my particular example for me to understand it well.
Error
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.
What causes error
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);
}
Item model
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; }
}
Category model
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; }
}
At first glance it seems to me that it is impossible to call something like Category.Items.Count() or Item.Category.Name using code-first, but I think I did something wrong with code because it should be possible. Please help, what should I do to make this work?
Category.Itemsshould be of typeICollection<Item>instead ofIQueryable<Item>