Reputation: 6368
I get an error as below:
'Object graph for type 'System.Collections.Generic.HashSet`1[[ERP_Lite_Data.
MenuItem, ERP_Lite_Data, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]'
contains cycles and cannot be serialized if reference tracking is disabled.
I have a table called MenuItems in my database. The fields and relationships in MenuItems is displayed in the image below:
The Class for this table generated by entity framework is as follows:
public partial class MenuItem
{
public MenuItem()
{
this.MenuItems1 = new HashSet<MenuItem>();
}
public int MenuItemID { get; set; }
public string Title { get; set; }
public Nullable<int> ParentID { get; set; }
public virtual ICollection<MenuItem> MenuItems1 { get; set; }
public virtual MenuItem MenuItem1 { get; set; }
}
I searched for the above error on internet and everywhere I get the same solution of applying DataMember attribute to the members of the class.So I have done that. Here is the modified MenuItem.cs.
[DataContract]
public partial class MenuItem
{
public MenuItem()
{
this.MenuItems1 = new HashSet<MenuItem>();
}
[DataMember, Key]
public int MenuItemID { get; set; }
[DataMember]
public string Title { get; set; }
[DataMember]
public Nullable<int> ParentID { get; set; }
[DataMember]
public virtual ICollection<MenuItem> MenuItems1 { get; set; }
[DataMember]
public virtual MenuItem MenuItem1 { get; set; }
}
But still I get the same error. Can anybody suggest me some workaround?
Update:
If I use the below method to return all the menuitems it works fine:
public IEnumerable<MenuItem> GetAllMenuItems()
{
using (Entities db = new Entities())
{
return (from m in db.MenuItems
select m).ToList();
}
}
The moment I change it to something like :
public IEnumerable<MenuItem> GetAllMenuItems()
{
using (Entities db = new Entities())
{
return (from m in db.MenuItems
select new MenuItem
{
MenuItemID = m.MenuItemID,
Title = m.Title,
ParentID = m.ParentID
}).ToList();
}
}
I get another error:
The entity or complex type 'Models.MenuItem' cannot be constructed in a LINQ to Entities query.
you may ask me to write code like below:
return (from m in db.MenuItems
select new
{
MenuItemID = m.MenuItemID,
Title = m.Title,
ParentID = m.ParentID
}).ToList();
Then what should be the return type of my method?
Upvotes: 1
Views: 1887
Reputation: 20203
Most famous question out there when it comes to serializing. Use projection into some type that does not have such references and avoid the exception.
In other words, pick up just the properties that you need from the EF model, do not add fields which are nested complex types that also have properties that point back to the same object and thus create circular references.
Upvotes: 2