Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serialization POCO proxy with WCF

When I run my service I got exception:

The server encountered an error processing the request. The exception message is 'Cannot serialize parameter of type System.Data.Entity.DynamicProxies.Cosik_14C2...' (for operation 'GetCosik', contract 'ICosikService') because it is not the exact type 'Project.Domain.Entities.Cosik' in the method signature and is not in the known types collection. In order to serialize the parameter, add the type to the known types collection for the operation using ServiceKnownTypeAttribute.'. See server logs for more details.

I'm new to WCF services and Entity Framework and I'd appreciate any help/suggestions.

I'm using Entity Framework 4.1. Using code-first I created database with two tables:

[DataContract(IsReference=true)]
public class Cosik
{
    [DataMember]
    public int cosikID { get; set; }

    [DataMember]
    public string title { get; set; }

    [DataMember]
    public int DifficultyID { get; set; }
    [DataMember]
    public virtual Difficulty Difficulty { get; set; }
}

[DataContract(IsReference=true)]
public class Difficulty
{
    [DataMember]
    public int DifficultyID { get; set; }

    [DataMember]
    [Required]
    public string NameToDisplay { get; set; }
}

Next I created the WCF service application and made it RESTful. Below is code for interface:

[ServiceContract]
public interface ICosikService
{
    [OperationContract]
    [ApplyDataContractResolver]
    [WebGet(UriTemplate = "/cosik")]
    Cosik GetCosik();
}

and implementation of that contract

public class RecipeService : IRecipeService
{
//repository of Cosik entities - stores collection of all
//Cosik entities that can be queried from DB
private ICosikRepository cosikRepo;
...

public Cosik GetCosik()
    {
        Cosik c = cosikRepo.GetById(1);
        return c;
    }

I implemented ApplyDataContractResolverAttribute class given on: http://msdn.microsoft.com/en-us/library/ee705457.aspx and added [ApplyDataContractResolver] annotation to GetCosik method. However, it didn't help.

Any suggestion what I've missed?

like image 695
anetafr Avatar asked Oct 08 '22 23:10

anetafr


1 Answers

Instead of developing custom resolver turn off proxy creation. Proxies are not for scenarios like WCF because lazy loading must be turned off anyway during serialization and dynamic change tracking is never used:

context.Configuration.ProxyCreationEnabled = false;
like image 144
Ladislav Mrnka Avatar answered Oct 13 '22 10:10

Ladislav Mrnka