c# - 是否可以在不创建 ViewModel 对象的情况下从 .NET 中的 REST api 获取复杂的 Entity Framework 对象?

标签 c# asp.net-mvc entity-framework asp.net-core entity-framework-core

想象一组 Entity Framework 实体:

public class Country {
    public string CountryCode { get; set; }
    public string Name { get; set; }
    public string Flag { get; set; }
}

public class Market {
    public string CountryCode { get; set; }
    public virtual Country Country { get; set; }
    public int ProductID { get; set; }      
    public virtual Product Product { get; set; }
}

public class Product {
    public int ProductID { get; set; }
    public string Name { get; set; }
    public virtual ICollection<Market> Markets{ get; set; }
}

想象一下 DOTNET 5 api GET

// GET api/product
[HttpGet]
public async Task<IActionResult> GetProduct([FromRoute] int id)
{
    return Ok(await _context.Products
        .Include(p => p.Markets)
        .SingleAsync(m => m.ProductID == id));
}

如果实体没有附加市场,数据会毫无问题地返回,但一旦我附加了一些链接项目,我就会收到错误消息:

HTTP Error 502.3 - Bad Gateway
The specified CGI application encountered an error and the server terminated the process.

我依稀记得以前的一个应用程序,其中每个复杂的 EF 对象都有一个“仅限基元”类型的对象来向客户端发送和接收此对象,但我想知道是否有一种无需中间对象即可进行通信的方法?

例如:

public class ProductViewModel {
    public int ProductID { get; set; }
    public string Name { get; set; }
    public List<MarketViewModel> Markets{ get; set; }
}

public class MarketViewModel {
    public int ProductID { get; set; }
    public Country Country { get; set; }
}

我担心的是从客户端来回翻译每个复杂对象的编码开销(我承认,我不确定这是否是一件坏事,也许无论如何都必须这样做)。

由于脚手架 API 似乎直接接受和返回实体,我发现自己想知道是否有一种方法可以直接处理对象的复杂部分

编辑#1:

根据下面 Noel 的评论,如果我将导致错误的代码更改为

    [HttpGet("{id}", Name = "GetProduct")]
    public async Task<IActionResult> GetProduct([FromRoute] int id)
    {

        Product product = await _context.Products
            .Include(t => t.Markets)
            .SingleAsync(m => m.ProductID == id);

        throw new System.Exception("error sample");
        return Ok(product);
    }

堆栈跟踪被正确抛出。如果我删除异常,则会出现 500 网关错误。我同意这看起来可能是序列化错误,但很难说。

EDIT 2 - 根据以下 Oleg 的评论:

坏网关的解决方案是首先在 project.json 文件的依赖项中显式更新更新版本的 NewtonSoft.Json:

"dependencies": {
  "Newtonsoft.Json": "8.0.1-beta3",

接下来您必须更改 Startup.cs 文件

    public void ConfigureServices(IServiceCollection services)
    {

         services.AddMvc()
            .AddJsonOptions(options => {
                options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
            });

有了这两个设置,错误的网关就不会再出现,并且 api 调用会按预期成功返回复杂对象。

最佳答案

在我看来,您只是在 SingleAsync 的调用中错过了 await。尝试使用

[HttpGet]
public async Task<IActionResult> GetProduct([FromRoute] int id)
{
    return Ok(await _context.Products
        .Include(p => p.Markets)
        .SingleAsync(m => m.ProductID == id));
}

更新:我找到了the issue .我建议您检查您可以检查 package.lock.json 以查看将通过自动解析依赖项加载哪个版本。那么我建议您在最新版本中明确添加Newtonsoft.Json 8.0.1-beta3到项目的依赖项。此外,您应该在 SerializerSettings.ReferenceLoopHandling 的配置中添加对 Newtonsoft.Json.ReferenceLoopHandling.Ignore 的设置。参见 the issue了解更多详情。

关于c# - 是否可以在不创建 ViewModel 对象的情况下从 .NET 中的 REST api 获取复杂的 Entity Framework 对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34290683/

相关文章:

c# - LINQ to Entities 无法识别 MVC5 中的方法 'System.DateTime ParseExact(System.String, System.String, System.IFormatProvider)' 方法错误

asp.net-mvc - EntityFramework 迁移指定 web.config

c# - 如何在 asp.net core web api 中绑定(bind) Json 查询字符串

c# - 任务错误处理-Visual Studio停止

c# - 递归方法的一部分可能不会在递归中执行

c# - 如何部署 "Release"版本的 ASP.NET MVC5 应用程序

asp.net-mvc - 即使在不同的区域, Controller 名称也必须是唯一的吗?

c# - "Error: Cannot Initialize OLE"当我尝试运行 SPA 时?

c# - 在运行时在 EF6 扩展 DbContext 类中创建 JOIN

c# - 单击 "OK"按钮时 Modalpopupextender 关闭