Search code examples
jsonopenrasta

OpenRasta Json returning nested classes


Is it possible to return nested classes in json with OpenRasta?

I'm using EF4.1 with code first (which in theory shouldn't make a difference, as they are just POCO classes).

Here is an example:

public class AppUser
{
    [Key]
    public int AppUserId { get; set; }
    public string WinLogin { get; set; }
    public string ScreenName { get; set; }
    public string AgencyId { get; set; }

    public virtual ICollection<UserAppVersion> UserAppVersion { get; set; }
}

public class UserAppVersion
{
    [Key]
    public int UaVersionId { get; set; }
    public int AppUserId { get; set; }
    public int AppVersionId { get; set; }
    public DateTime DateCreated { get; set; }
    public DateTime DateUpdated { get; set; }

    public virtual AppUser User { get; set; }
    public virtual AppVersion Version { get; set; } 
}

I try and return an AppUser record in json using this:

ResourceSpace.Has.ResourcesOfType<AppUser>()
    .AtUri("/user").HandledBy<UserHandler>().AsJsonDataContract();

But I get an error:

System.Runtime.Serialization.SerializationException: Type 'System.Data.Entity.DynamicProxies.UserAppVersion_FD8D86F0A3AE39A0C370918637C1A90AD8D3ACA3E149677EA82C0A8D10ED0F8D' with data contract name 'UserAppVersion_FD8D86F0A3AE39A0C370918637C1A90AD8D3ACA3E149677EA82C0A8D10ED0F8D:http://schemas.datacontract.org/2004/07/System.Data.Entity.DynamicProxies' is not expected. Consider using a DataContractResolver or add any types not known statically to the list of known types - for example, by using the KnownTypeAttribute attribute or by adding them to the list of known types passed to DataContractSerializer.

Unfortunately I don't know how to resolve this. Any suggestions?


Solution

  • That's a data contract issue, not an openrast one.

    The DataContract serialzier is seeing a dynamic proxy probably generated by EF code first, and when seeing that cannot render the object.

    I'd recommend either swapping for another serialziation codec, or disabling transparent lazy loading, or alternatively marking your property as an ignore for serialziation and have another property typed to a List so the serializer can function.

    See DataContractSerializer Error using Entity Framework 4.0 with WCF 4.0