2
votes

I have got a class which has many virtual properties lazy loaded

public class TestPlan
{
    public virtual ICollection<Test> Test { get; set; }
    public virtual Commercial Commercial { get; set; }
    ...
}

and this class has to be serialized later in the program. The thing is, as those properties are virtual I've got an error (circular reference) everytime I try to serialize it. Now here is my question:

My boss told me to use what he calls View Object which is the same object but without the unused properties. What do you think of this? Should I set those unused properties to null or something?

Background:

The serialized object is meant to be used in an infragistics grid (a nice array). I've already tried using the [ScriptIgnore] attribute on my virtuals but it didn't worked.

I also tried retrieving my TestPlans as database.TestPlans.AsNoTracking().ToList() but got an error (When an object is returned with a NoTracking merge option, Load can only be called when the EntityCollection or EntityReference does not contain objects.)

Thanks in advance

1
This kind of object could be called a ViewModel or a DTO, depending on its usage.MattDavey
Beat me with this one, i have to type faster ;)sanosdole
@MattDavey i will use DTO, thanksTitouan D.

1 Answers

1
votes

If your Boss means a DataTransferObject with View Object he seems to be going in the right direction. This is sometimes also called a ViewModel object in ASP. This is just a plain POCO representing a flattened Version of your Model Objects (some use AutoMapper for the flattening)

You should not modify your model objects but instead create a new object (possibly flattened) for the purpose of serialization. This object has no behaviour just data and represents the contract for serialization.

I cannot see a circular reference from your example code, but if you want i may give you an unrelated code example that shows how to resolve circular references by flattening. (Difficult to do without knowing the model)