I have following models:
public class Category
{
public virtual ICollection<Product> Products{get;set;}
public Product()
{
Products = new HashSet<Product>();
}
}
public class Product
{
public Guid CategoryId{get;set;}
public virtual Category {get;set;}
}
Now if I execute following statement:
var list = await UoW.Categories.Query.Where(x=>x.Name.Contains("Mob")).ToListAsync();
and return list
as JSON
from MVC controller action. It throws following exception:
A circular reference was detected while serializing an object of type
'System.Data.Entity.DynamicProxies.Category_7C2191CFExxxxxxx'.
It is happening because Products
collection is not null and each Product
in turn contains Category
.
What is the reason for virtual properties getting uploaded automatically?
EDIT:- It turns out Json Serializer was accessing properties and causing EF to load them. I have turned LazyLoading
off as suggested by haim770.