I have a problem when sending Entity Framework-generated entities with navigation properties over WCF. I have a Securities database for storing financial data and two tables inside it:
Stock : Id, Symbol, CompanyName, ExchangeName
Option: Id, StockId, OptionType, Strike
I created an Entity Framework model for this database. Then I created WCF service which exposes generated Stock and Option EF entities to the clients.
My generated entity Stock has navigation property EntityCollection<Option> Options.
When trying to return Stock entity from WCF service to the client, I get an SerializationException: WCF cannot serialize Options navigation property because database connection has been already closed.
I can call Options.Load() method when database connection is opened to fill Options property, but what should I do if I don’t want to load full object graph for Stock entity?
I’ve fought with this one for a while.
First, I turned lazy loading off. But I still had problems with cycles in my object graph.
Then, I put
[DataContract(IsReference = true)]tags on all of my entities. That worked, but I still had a lot of performance issues do to a denormalized database.Finally, I broke down and make dtos and I use AutoMapper to populate them.
One of my coworkers told me to do this from the beginning, and I should have just listened to him. Do yourself a favor and don’t make the same mistake that I did.
Edit
I forgot to mention that I had issues deserializing entities that has properties of type
ICollection<T>. These will deserialize as arrays. SomehowT[]implementsICollection<T>butAddandRemovewill throw exceptions. This was another reason to use DTOs.