I had same problem, it seams that the DataContractSerializer
has a problem with the navigation properties of ef objects.
In my test project, I'm using the northwind database. I wanted to test the CodeFirst approach with the recommended DbContext.
The provided navigation properties are virtual and they are loading on demand, but the ef just return with the first level of the entity on navigation properties is filled.
On serializing the entity object the DataContractSerializer failed because the entity object is no longer bound to the DbContext and the serialization of the navigation properties failed.
This is happen when I try to consume a NW Employee object over my wcf service.
My soultion is to copy all data in a new object with the data contract attributes!
the service call:
public IEnumerable<EmployeeWcf> GetAll()
{
IEnumerable<EmployeeWcf> result = null;
result = from e in context.Employees.OrderBy( e => e.LastName )
select new EmployeeWcf
{
EmployeeId = e.EmployeeID,
Firstname = e.FirstName,
Lastname = e.LastName
};
return result;
}
the class:
[DataContract]
public class EmployeeWcf
{
[DataMember]
public int EmployeeId { get; set; }
[DataMember]
public string Firstname { get; set; }
[DataMember]
public string Lastname { get; set; }
}
This work but it seems to me that this is not a perfect solution.
I hope this helps you.