Reputation: 159
I have a class 'Entity'
[Serializable]
public class Entity
{
public Guid Id { get; set; }
public IEnumerable<Entity> ChildEntity { get; set; }
}
I would notice that it has property ChildEntity which is a list of same class Entity.
Question1. Do I have to explicitly serialize this list ? Or Serializable attribute on the class will do that work for me.
Now when I try to Serialize this class using Binary Serializer I get exception saying this class is not marked as Serializable.
I think the exception occurs when it tries to serialize childEntities.
Here is my code for serializing.
public static T DeepClone<T>(T obj)
{
using (var ms = new MemoryStream())
{
var formatter = new BinaryFormatter();
try
{
formatter.Serialize(ms, obj);
}
catch (Exception Ex)
{
//TODO
}
}
}
I also have a class from where the List of Entity Class is getting populated.
[Serializable]
public class AllEntity
{
public Guid ParentId {get; set; }
public Guid Id {get; set;} //childId
public string Desc {get; set;}
}
I am performing recursion to build the List of Entity class based on Parent Child Relationship.
public IEnumerable<Entity> Build(IEnumerable<AllEntity> allentity)
{
//recursivey builds List if Entity class
}
Exception Message:
Type 'System.LINQ.Enumerable+WhereSelectListIterator`2[[Common.Models.AllEntity, Common, Version=1.0.0.0, Culture=neutral, Token=null], [Common.Models.Entity, Common, Version=1.0.0.0, Culture=neutral, Token=null]' in Assembly 'System.Core, Version=4.0.0.0, Culture=neutral, Token=null' is not marked as Serializable
Upvotes: 4
Views: 4964
Reputation: 116526
As indicated by the exception, your problem is that, in at least one Entity
instance, the property IEnumerable<Entity> ChildEntity
does not actually refer to a List<ChildEntity>
, it refers to the unevaluated result of a .Where()
. LINQ query.
Materialize it with ToList()
before storage.
Upvotes: 5
Reputation: 290
I have checked with below code its working fine.
Entity ea = new Entity();
ea.Id = Guid.NewGuid();
var li = new List<Entity>();
li.Add(new Entity { Id = Guid.NewGuid() });
ea.ChildEntity = li;
DeepClone<Entity>(ea);
Just you need to mark class as [Serializable].
Upvotes: 0