Austin Austin -4 years ago 163
C# Question

asp.net entity framework keys in response

I am trying to write my first RESTful API in C# using ASP.NET Web API and Entity Framework.

My issue is that the list that returns from my EF query is polluted with entity key information that is useless (I found out that because my columns are nullable if thinks they all must be keys).

Here is a part of the XML response I receive from my API call

<syemploy z:Id="i1"><EntityKey z:Id="i2">
<d2p1:EntityContainerName>AbraHRMS_LiveEntities</d2p1:EntityContainerName>
<d2p1:EntityKeyValues>
<d2p1:EntityKeyMember>
<d2p1:Key>id_col</d2p1:Key>
<d2p1:Value i:type="d5p1:int">15</d2p1:Value>
</d2p1:EntityKeyMember>
<d2p1:EntityKeyMember>
<d2p1:Key>e_address1</d2p1:Key>
<d2p1:Value i:type="d5p1:string">153 Townsend Street, Suite 9057</d2p1:Value>
</d2p1:EntityKeyMember>
...


How can I remove the entity key values from the response?
My c# code looks like this

AbraHRMS_LiveEntities _db = new AbraHRMS_LiveEntities();

# GET api/employee
public List<MvcApplication1.DAL.syemploy> Get()
{
return _db.syemploys.ToList();
}


Again, this is my first API in C#, so if anything is funky looking please feel free to point it out.

Answer Source

By default you'll have all public properties of your entities in XML. To avoid having them in response, try to create "new" class which doesn't contain undesirable fields and then convert your result to the list of "new" type objects. You can use .Select() or .Cast() on _db.syemployes for that. Keep in mind that syemploy class should be convertible to "new" class in case you want to call Cast<> method. You can read here about type conversion in C#. If you use .Select() then construct objects of new type inside of select's lambda expression.

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