【问题标题】:when the related data is included using fluent api, the list not populated in ajax (using Web Api)当使用 fluent api 包含相关数据时,列表不会在 ajax 中填充(使用 Web Api)
【发布时间】:2015-03-15 04:47:34
【问题描述】:

在我的 ASP.NET Web 窗体应用程序(使用代码优先的 EF 和 Web Api)中,我需要使用 ajax 读取项目列表 (List<Post>) 并使用以下代码填充帖子列表。但是,我遇到了一个奇怪的问题,如下所述。

 function LoadPostsByTimeframe(currTimeframeId) {
        jQuery.support.cors = true;
        $.ajax({
            url: '/api/post/GetPostsByTimeframe?tfId=' + currTimeframeId,
            type: 'GET',
            contentType: "application/json; charset=utf-8;",
            dataType: 'json',
            success: function (response) {
                var posts = response.d;
                //do stuff
            },
            error: function (x, y, z) {
                alert(x + '\n' + y + '\n' + z);
            }
        });
    }

在我的控制器类中,当我使用以下方法检索项目列表时:

[ScriptMethod(ResponseFormat = ResponseFormat.Json)] 
    public IList<Post> GetPostsByTimeframe(int tfId)
    {
        gEchoLuDBContext db = new gEchoLuDBContext();
        var posts = db.Posts.Where(p=>p.TimeFrameId == tfId).ToList();

        return posts;           
    }

我得到了正确的每一个项目(第三个不适合碎石)

但是,我需要检索每个项目的相关人员数据。因此,我需要使用以下代码(带有Include)来检索项目。

[ScriptMethod(ResponseFormat = ResponseFormat.Json)] 
    public IList<Post> GetPostsByTimeframe(int tfId)
    {
        gEchoLuDBContext db = new gEchoLuDBContext();
        var posts = db.Posts.Include(po=>po.Person).Where(p=>p.TimeFrameId == tfId).ToList();

        return posts;           
    }

我有这个输出(只返回第一项,其他两项为空):

在这两种情况下(无论是否包含),Controller 方法都会返回一个包含所有项目的有效List&lt;Post&gt;。但是,对于 Include 版本,列表值(第一个值除外)不会显示在 ajax/jquery 端。

你认为我遗漏了什么吗?

【问题讨论】:

    标签: c# asp.net ajax entity-framework asp.net-web-api


    【解决方案1】:

    尝试在.ToList() 之前添加.AsNoTracking()

    【讨论】:

    • 是的,成功了!你能解释一下吗?我找到了这个解释,但不太明白:返回一个新查询,其中返回的实体不会缓存在 DbContext 或 ObjectContext 中。
    • 使用 AsNoTracking 的部分原因是实体成为原始 POCO 对象,而不是可以作为引用的代理 POCO 对象(使用指针指向已在内存中的对象,而不是拥有多个副本) .
    • 但是,我不明白为什么它会在我的场景中造成麻烦?
    • 简单的答案是您不应该像以前那样序列化代理的 POCO 类,因为有时您可能无法获得预期的结果。也许你打开了延迟加载?
    猜你喜欢
    • 2016-03-19
    • 2021-01-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-13
    • 2018-09-07
    • 1970-01-01
    相关资源
    最近更新 更多