Say you have a one to one relationship in your entity model. The code generator will decorate it with the following attributes:
[global::System.Xml.Serialization.XmlIgnoreAttribute()]
[global::System.Xml.Serialization.SoapIgnoreAttribute()]
public RelatedObject Relationship { get {...} set {...} }
I want to serialize my parent object together with all its properties for which data has been loaded through an XML web service. Obviously, these related properties do not get serialized because of these attributes.
So for my purposes I just want to remove these “don’t serialize me” attributes. I can do a find and replace in the designer code, but any modifications I make in the designer will put these attributes back in.
In my query I’m .Include()ing and explicitly loading only the child objects that I require for serialization. So I will make sure there are no circularities in my query. Some of the child properties are not required, so I won’t Include() them, so they won’t be serialized.
Else how do I achieve what I want to do? Make a separate call from my application for each child object? Say I’m returning hundreds of parent objects; I’d have to make hundreds of separate calls to get each child too.
How do I permanently get rid of these attributes?
VS 2008 / EF 3.5.
Here is a little known fact… Entity Framework + Web Services = :'(
There are three(3) approaches that can be taken to solve your problem (namely the XML graph serialization problem… or the lack of it).
I will list each approach in order of least development time and complexity of implementation required [“Bang-For-Buck”] vs. scalability, maintainability and performance [“Future Proofing”].
Create POCO classes for each Entity for projection when sending over the wire. This is the easiest (and monotonous) approach but will solve your problem. I have included a sample at the end.
Use WCF to relay your data. Entity Framework and WCF are like ‘brothers from a different mother’. They were designed to work together but share their differences. You will notice that all EF generated Entity Objects are inherently [DataConctract] with all fields being [DataMember]. This makes use of the WCF DataContract Serializer with handles graphs very efficiently and maintains object reference even after deserialization. WCF DataContract Serializer is also proven to be 10% quicker than your default XML Serializer.
Use EF 4.0 Self Tracking Entities (STE). This is still very new but it is workable. In Visual Studio 2010 you are given an option to generate Self Tracking Entities which are designed for N-Tier and SOA. The best thing about STE is the usage of T4 Transformed Text templates to generate the code. The classes generated by T4 is clean and very malleable, giving you plenty of room to insert your logic and validation. Here is a link to STE tutorial to get your started.
Best of luck and I hope you find the best approach for you.
POCO example.
And your [WebMethod] is something like this.