I have a database with Car Histories. Each car history has multiple images associated with it. I am using NHibernate 2.2 to set up the relationships and the CarHistory mapping contains a bag for the images:
<bag name="Photos" table="DetailPhoto" cascade="all" lazy="true">
<key column="CAR_DETAIL_ID"/>
<one-to-many class="DetailPhoto"/>
</bag>
I have an iPad app which communicates with the server using JSON. I want to load all of the car history items into a list on the iPad and I don't want to include the photos when loading the list because it slows down the data retrieval which is why I have made the Photos lazy.
When I try and use JsonConvert.SerializeObject to serialize my list of Car Histories I get a lazy initialization exception which is because I have loaded my objects and closed the session already because I don't need the photos and the JsonSerializer is touching all of the properties on the object.
I would like to return the Json data to the client without the photos but I cannot use the ignore JsonProperty on my object because I want to load this collection in other situations.
I have tried this but it just does the same thing giving me the lazy initialization exception: http://www.royjacobs.org/2011/07/27/using-json-net-to-serialize-proxied-nhibernate-objects/
This is my CarHistory (CarDetail) class
public class CarDetail
{
[JsonProperty("id")]
public virtual int Id { get; set; }
[JsonProperty("carId")]
public virtual int CarId { get; set; }
[JsonProperty("date")]
public virtual DateTime ? Date { get; set; }
[JsonProperty("details")]
public virtual string Details { get; set; }
[JsonProperty("photos")]
public virtual IList<DetailPhoto> Photos { get; set; }
}
So my question is how can I retrieve a list of CarHistories without the associated Photos in some circumstances and not others?