c# - Should I always use navigation properties or use the .Where query? -


this question whether approach better or whether it's insignificant @ all. so, have class item so

public class item {     public int id { get; set; }     public string name { get; set; }     public virtual icollection<category> categories { get; set; } } 

and referenced 1 category

public class category {     public int id { get; set; }     public string name { get; set; }     public virtual icollection<item> items { get; set; } } 

the problem when user clicks on category, items within category should outputted in list, , should categories of item.

i use

_context.items.where(c => c.category.id == id); 

and remove virtual member. reason why ask , why "want" remove member because when use webapi json data of items table client outputs this:

{     "id": 1,     "name": "string",     "category": [         {         "id": 1,         "name": "cname",         "items": []         },          {         "id": 1,         "name": "cname",         "items": []         }     ] } 

so problem having navigation property category model send me "items": [] when request list of items. it's not it's affecting me or anything, want know whether should use navigation approach or .where approach. or maybe there other way should consider?

always use navigation properties. ef able generate far more efficient query (likely, @ least). much easier read.

that said. not use ef objects data contracts. running 1 through serializer will, in best case have above, , in common case cause circular reference exception.

your contracts should defined separately circular references not exist. use select convert collections db type api type.


Comments