'ObjectContent`1': Failed to serialize the response from DbSet

僤鯓⒐⒋嵵緔 提交于 2020-07-08 03:38:12

问题


I have the following controller in TabletController.cs file:

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); 
        }
    }
}

I'm trying to call:

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

But I get the following error:

Call isdDbSet

Also, I need to get the results of the table's fields in json format. I tried to serialize it in JSON, but I get the same error.

<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>

My WebApiConfig.cs file is:

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 }
        );
    }
}

Also, my RouteConfig.cs is:

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:


I found the solution.

I've changed the TableController.cs file to

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));
        }
    }


来源:https://stackoverflow.com/questions/61667918/objectcontent1-failed-to-serialize-the-response-from-dbset

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!