I have been trying out both Linq to Sql and EF in my ASP.NET MVC application. After switching to EF I realized my XML/JSON serialization output has extra cruft.
XML:
<Test xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:xsd='http://www.w3.org/2001/XMLSchema'> <EntityKey> <EntitySetName>Persons</EntitySetName> <EntityContainerName>PersonEntities</EntityContainerName> <EntityKeyValues> <EntityKeyMember> <Key>Id</Key> <Value xsi:type='xsd:int'>1</Value> </EntityKeyMember> </EntityKeyValues> </EntityKey> <Id>1</Id> <Name>John</Name> </Test>
JSON:
{'Id':1,'Name':'John','EntityState':2,'EntityKey'{'EntitySetName':'Persons','EntityContainerName':'PersonEntities','EntityKeyValues':[{'Key':'Id','Value':1}],'IsTemporary':false}}
Instead I would just like my output to be:
{'Id':1, 'Name':'John'}
My EF query to retrieve the object is:
Tests.First(t => t.Id == testId);
You can shape the JSON result in your controller like this:
This will limit the DTO which is serialized to contain only the values you want.
Edit: As a paritial answer to your comment question; you can create a simpler PersonViewModel class (DTO) that you can map the properties to. As John Saunders mentioned in his answer Automapper is a nice way to simplify the copying of the property values out of the EF Person instance:
The modified Action method may look like this:
The only other option I can think of is to use reflection to modify the DataMemberAttributes on the Person entity to suppress the EntityKey property.