'ObjectContent`1': не удалось сериализовать ответ от DbSet - PullRequest
0 голосов
/ 08 мая 2020

У меня в файле TabletController.cs есть следующий контроллер:

public class TabletController : ApiController
{
    public IQueryable Get(int c_id)
    {
        using (EMSMVCEntities entities = new EMSMVCEntities())
        {
            return entities.Calls.Where(e => e.call_id == c_id); 
        }
    }
}

Я пытаюсь позвонить:

http://localhost:53366/api/Tablet/157

Но получаю следующую ошибку:

Call это dDbSet

Кроме того, мне нужно получить результаты полей таблицы в формате json. Я попытался сериализовать его в JSON, но получаю ту же ошибку.

<ExceptionMessage>
Type 'System.Data.Entity.Infrastructure.DbQuery`1[[EMSMVC.Models.Call, EMSMVC, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]' with data contract name 'ArrayOfCall:http://schemas.datacontract.org/2004/07/EMSMVC.Models' is not expected. Consider using a DataContractResolver if you are using DataContractSerializer or add any types not known statically to the list of known types - for example, by using the KnownTypeAttribute attribute or by adding them to the list of known types passed to the serializer.
</ExceptionMessage>
<ExceptionType>
System.Runtime.Serialization.SerializationException
</ExceptionType>

Мой WebApiConfig.cs файл:

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        // Web API configuration and services

        // Web API routes
        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "TabletCallApi",
            routeTemplate: "api/{controller}/{c_id}",
            defaults: new { controller = "Tablet", action = "Get" }
            );

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    }
}

Кроме того, мой RouteConfig.cs:

public class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Dashboard", action = "Index", id = UrlParameter.Optional }
        );
    }
}

1 Ответ

1 голос
/ 08 мая 2020

Я нашел решение.

Я изменил файл TableController.cs на

public System.Web.Http.Results.JsonResult<Call> Get(int c_id)
    {
        using (EMSMVCEntities entities = new EMSMVCEntities())
        {
            entities.Configuration.ProxyCreationEnabled = false;
            return Json(entities.Calls.FirstOrDefault(e => e.call_id == c_id));
        }
    }
...