Artsiom Che Artsiom Che - 1 year ago 198
C# Question

'ObjectContent`1' type failed to serialize generic collection

How to setting generic collection to serialize in web api?
I have thess classes

public partial class User:BaseEntity
[Required,MaxLength(100), MinLength(5)]
[Index(IsUnique = true)]
public string Login { get; set; }

[Required, MaxLength(100), MinLength(64)]
public byte[] Password { get; set; }

public string Email { get; set; }

[MaxLength(40), MinLength(4)]
[Index(IsUnique = true)]
public string NickName { get; set; }

[MaxLength(100), MinLength(4)]
public string FullName { get; set; }

public virtual ICollection<Group> Groups { get; set; }
public virtual ICollection<Location> Locations { get; set; }

public class UsersController : ApiController
public IEnumerable<User> GetAllUser()
using (var repoProvider = new RepositoryProvider())
return repoProvider.Get<UserRepository>().GetAll();

How we can see User have generic collection properties. And when I try to launch the application I have this error


<Message>An error has occurred.</Message>

<ExceptionMessage>The 'ObjectContent`1' type failed to serialize the response body for content type 'application/xml; charset=utf-8'.</ExceptionMessage>




<Message>An error has occurred.</Message>

<ExceptionMessage>Type 'System.Data.Entity.DynamicProxies.Users_0D7A537351492F8D419F58EA70B1240500CF0FFF354951D83FA225EA973C5338' with data contract name

'Employee_0D7A537351492F8D419F58EA70B1240500CF0FFF354951D83FA225EA973C5338:' 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.</ExceptionMessage>


How to resolve this problem?

Answer Source

The problem can have two causes

  1. You have dynamic proxies enabled in EF, and you're sending to the browser an entity which doesn't have the original type Users but the dynamic class with a very long name that you can see in the exception message: Users_0D7A53..

  2. The entity isn't configured to be (de)serialized with the DataContractSerializer (i.e. is not serializable)

The solution for the first is to disable dynamic proxy creation on EF or using the AsNoTracking extension method on the query to avoid the generation of the proxy.

Related docs:

The second part is not probable to be the root of the problem. To solvethis, basically you can use the serialization attributes: [DataContract], [DataMember] and so on.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download