【问题标题】:Problem when I Try to return a query including a navigation property using an API Controller当我尝试使用 API 控制器返回包含导航属性的查询时出现问题
【发布时间】:2018-11-06 11:29:24
【问题描述】:

我正在编写我的第一个 API 控制器,但是当我尝试包含导航属性时遇到问题,例如:当我进行类似的查询时

    public IEnumerable<Batch> GetByItemId(long itemId)
    {
         return context.Batch.Where(b => b.ItemId == itemId).ToArray();// It works 
    }

我得到了预期的结果(使用 powershell):

Invoke-RestMethod http://localhost:5000/api/batch/10 -Method Get

id             : 50
creationDate   : 2018-11-04T00:46:05.665537
itemId         : 10
item           : 
expirationDate : 2019-01-16T00:00:00
batchLocations : 

id             : 65
creationDate   : 2018-11-04T01:30:54.492142
itemId         : 10
item           : 
expirationDate : 2019-01-01T00:00:00
batchLocations : 

但是当我尝试包含 BatchLocation 导航属性时:

    public IEnumerable<Batch> GetByItemId(long itemId)
    {
        return context.Batch
           .Where(b => b.ItemId == itemId)
           .Include(b => b.BatchLocations)
           .ToArray();
    }

GetByItemId 方法返回预期的 IEnumerable(我已对其进行调试),但出现以下错误:

Invoke-RestMethod http://localhost:5000/api/batch/10 -Method Get
Invoke-RestMethod : Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host.
At line:1 char:1
+ Invoke-RestMethod http://localhost:5000/api/batch/10 -Method Get
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo          : NotSpecified: (:) [Invoke-RestMethod],     IOException
+ FullyQualifiedErrorId : System.IO.IOException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand


    [Route("api/[controller]")]
    public class BatchController : Controller
    {
    private IUnitOfWork unitOfWork;

    public BatchController(IUnitOfWork unitOfWork)
    {
        this.unitOfWork = unitOfWork;
    }
    [HttpGet("{id}")]
    public IEnumerable<Batch> GetById(long id) => unitOfWork.Batchs.GetByItemId(id);
    }

存储库代码:

    public class Repository<T> : IRepository<T> where T : class
    {
      protected readonly AppDbContext context;
      public Repository(AppDbContext ctx) => context = ctx;
    }

    public class BatchRepository : Repository<Batch>, IBatchRepository
    {
      public BatchRepository(AppDbContext ctx) : base(ctx)
      {}
      public IEnumerable<Batch> GetByItemId(long itemId)
      {
        return context.Batch.Where(b => b.ItemId == itemId).Include(b => b.Item).ToArray();// Problem 
        // return context.Batch.Where(b => b.ItemId == itemId).ToArray();  //It works
      }
    }

带有调试信息的屏幕截图:

Debugging Info

当我尝试使用 React 使用 Api 控制器时

import React, { Component } from 'react'

class ItemInfo extends Component {
    constructor(props) {
        super(props);
        this.state = { batchs: [] };
        this.renderBatchs = this.renderBatchs.bind(this);
        fetch('api/batch/'+this.props.itemId)
            .then(response => response.json())
            .then(batchInfo => {
                this.setState({ batchs: batchInfo });
            }).catch(function (error) {
                console.log('There has been a problem with your fetch operation: ', error.message);
        });;
    }

renderBatchs() {
    return (
        <table>
            <thead>
                <tr><th>Id</th></tr>
            </thead>
            <tbody>
                    {this.state.batchs.map((batch, index) => (
                        <tr key={index}><th>{batch.id}</th></tr>
                    ))}
            </tbody>
        </table>
        )
}

render() {
    const batchs = this.renderBatchs();
    return (
        <div>
            {batchs}
        </div>
        )
    }
}

export default ItemInfo;

我收到以下控制台消息:

GET http://localhost:5000/api/batch/1 net::ERR_CONNECTION_RESET
There has been a problem with your fetch operation:  Failed to fetch

我不知道为什么,任何建议或参考将不胜感激。

【问题讨论】:

  • 如何在存储库方法中获取上下文?是被注射了吗?
  • 我添加了附加代码,但我认为问题不存在。
  • 我怀疑问题出在控制器上 - 我怀疑您的数据模型存在问题。如果您还没有测试过您的存储库,请尝试编写单元测试以查看是否可以直接调用该方法。然后你会得到一个正确的错误消息,或者至少证明你的数据模型是好的。
  • 我添加了一个带有调试信息的屏幕截图,我只是在学习,但看起来还可以。感谢您的宝贵时间。

标签: rest asp.net-core entity-framework-core


【解决方案1】:

由于使用 React 发现的错误,我发现了这篇文章 ERR_CONNECTION_RESET returning Async including object child collections,这与使用相同解决方案的问题相同:我在 Batch 和 Item 模型上都有导航属性,并且我正在重新使用持久性模型,我只是没有不知道这个"DO. NOT. USE. PERSISTENCE. MODELS. AS. RETURN. OF. ACTIONS"。然后我创建了一个 ViewModel,一切正常。

【讨论】:

    猜你喜欢
    • 2023-03-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多