I am developing my first web application using MVC5+WebAPI2 with the EntityFramework 5.0.
In my application I have to display a list of transactions extracted from a database, so I have a WebApi Controller which does the following:
[RoutePrefix("api/transaction")]
public class TransactionApiController : ApiController
{
[Route("{userid}/{status}")]
[HttpGet]
[Authorize]
public TPASS_Transaction[] getTransactions(string userid, int status) {
using (var ec = new TelepassEntities()) {
TPASS_Transaction[] transactions = ec.TPASS_Transaction
.Where(t => t.TransactionOwner.EndsWith(userid) && t.Status == status)
.ToArray();
return transactions;
}
}
}
However, on the client I get an error: The 'ObjectContent`1' type failed to serialize the response body. It seems like this is due to the property HBTI_Employee in the TPASS_Transaction class:
"InnerException":{"Message":"An error has occurred.",
"ExceptionMessage":"Error getting
value from 'HBTI_Employee1' on
'System.Data.Entity.DynamicProxies.HBTI_Employee_...
My workaround to this problem was to create a class TransactionViewModel, and create objects of this type on the server from the original TPASS_Transaction, avoiding the HBTI_Employee property:
[Route("{userid}/{status}")]
[HttpGet]
[Authorize]
public TransactionVM[] getTransactions(string userid, int status) {
using (var ec = new TelepassEntities()) {
TransactionVM[] transactions = ec.TPASS_Transaction
.Where(t => t.TransactionOwner.EndsWith(userid) && t.Status == status)
.Select(t => new TransactionVM()
{
//all properties of TPASS_Transaction
//but HBTI_Employee
}).ToArray();
return transactions;
}
}
Anyway, it would be tedious to do it for every model class in my application, so I would rather work with the original objects. I googled the issue, but no one seems to give a good answer/solution to this problem. Can anyone explain what is wrong/what I am missing here?