Problem with Entity Framework objects: Cannot serialize member... because it is an interface.

Topics: Web Api
Nov 30, 2011 at 8:17 AM
Edited Nov 30, 2011 at 8:23 AM

inside one of my services I used the object which directly comes from entity framework and I got the following error:

Cannot serialize member DataAccess.SqlServer.Resort.AccommProperties of type System.Collections.Generic.ICollection`1[[DataAccess.SqlServer.AccommProperty, DataAccess, Version=1.0.4350.30311, Culture=neutral, PublicKeyToken=null]] because it is an interface.

This is the code of my service:

 

        [WebGet]
        public HttpResponseMessage<IQueryable<DataAccess.SqlServer.Resort>> GetAll() {

            var resorts = _resortRepo.GetAll(
                    ApprovalStatus.Approved
            );

            var resortsResponse =
                new HttpResponseMessage<IQueryable<DataAccess.SqlServer.Resort>>(resorts);
            resortsResponse.Content.Headers.Expires = new DateTimeOffset(DateTime.Now.AddHours(6));
            return resortsResponse;

        }

 

The below is the Resort class which I am trying to expose above:

 

    public partial class Resort
    {
        public Resort()
        {
            this.AccommProperties = new HashSet<AccommProperty>();
            this.ResortDetails = new HashSet<ResortDetail>();
        }
    
        public int ResortID { get; set; }
        public int DestinationID { get; set; }
        public System.Guid ResortGUID { get; set; }
        public Nullable<int> SecondaryID { get; set; }
        public string ResortName { get; set; }
        public Nullable<bool> IsApproved { get; set; }
        public string ResortType { get; set; }
    
        public virtual ICollection<AccommProperty> AccommProperties { get; set; }
        public virtual Destination Destination { get; set; }
        public virtual ICollection<ResortDetail> ResortDetails { get; set; }
    }

Like the error message says, I can't serialize an interface. but what am I supposed to do all of EF objects? 

Nov 30, 2011 at 11:15 PM

Hi Tugberk,

DataContractSerializer does not support interfaces in general, but it does special-case the IEnumerable collection interface. So you should be able to replace all the ICollections with IEnumerable and have everything work.

Hope that helps,

Youssef

Dec 1, 2011 at 7:46 AM

Hi Youssef,

Thanks for you response. I am working with DB first approach with EF 4.2 and I am occasionally updating my model from DB. So, if I tweak the generated codes to change from ICollection to IEnumerable, they will be back to same when I update them.

So, this will be a pain but I understand that this is the only way. Thanks!

Dec 1, 2011 at 3:40 PM
Edited Dec 1, 2011 at 3:40 PM

Try something like automapper to map to Data Transfer Objects or something besides your data access objects.