我刚刚将我的ASP Web API项目从.Net core 2.0升级到3.0。我在用
services.AddMvc()
.AddJsonOptions(options =>options.SerializerSettings.ContractResolver
= new DefaultContractResolver());
Run Code Online (Sandbox Code Playgroud)
以前是为了确保序列化JSON的小写字母。
升级到3.0后,出现此错误...
错误CS1061'IMvcBuilder'不包含'AddJsonOptions'的定义,找不到可以接受的扩展方法'AddJsonOptions'接受类型为'IMvcBuilder'的第一个参数(是否缺少using指令或程序集引用?)
根据Asp.Net Core 2.2中MvcJsonOptions的AddJsonOptions,Microsoft.AspNetCore.Mvc.Formatters.Json nuget包提供了AddJsonOptions扩展方法。我尝试安装/重新安装此程序,但仍然无法解决该方法。有趣的是,智能感知仅显示Microsoft.AspNetCore.Mvc.Formatters。即使我添加了Json nuget包,当我尝试添加using语句时也使用Xml。
有什么想法吗?该文档为AddJsonOptions只上升到.NET 2.2所以也许是方法已经在3.0赞成一些其他配置机制的被弃用?
假设我的一个控制器中有这样的方法:
[Route("api/Products")]
public IQueryable<Product> GetProducts() {
return db.Products
.Include(p => p.Category);
}
Run Code Online (Sandbox Code Playgroud)
使用这个我可以从数据库中获取产品并包含其Category属性.
在我的CategoryControllerI中有这个方法:
[Route("api/Categories")]
public IQueryable<Category> GetCategories() {
return db.Categories
.Include(c => c.Parent)
.Include(c => c.Products)
.Include(c => c.SubCategories);
}
Run Code Online (Sandbox Code Playgroud)
当我向CategoryController发送GET请求时,它按预期工作,我得到类别,其父级,产品和子类别.但是,当我向ProductController发送GET请求时,我不想将所有产品都包含在所请求产品的类别中,我只需要有关该类别的基本信息.
那么,我如何让GetProducts()返回数据库中的产品,包括每个产品的Category属性,但不包括该类别的Products列表属性,仍然保留其他属性,如id,title等?
谢谢.
我有一个包含表/数据的数据库,因此我使用了数据库优先方法,使用以下命令来搭建模型:
dotnet ef dbcontext scaffold "Server=.;Database=MyDb;Trusted_Connection=True;" Microsoft.EntityFrameworkCore.SqlServer -o Models
Run Code Online (Sandbox Code Playgroud)
这已经生成了DbContext与我的表相对应的两个模型类。这个问题只涉及2个模型,所以我提供以下代码:
人.cs:
using System;
using System.Collections.Generic;
namespace MyApp.Models
{
public partial class Person
{
public Person()
{
Profiles= new HashSet<Profile>();
}
public int Id { get; set; }
public string Email { get; set; } = null!;
public string Password { get; set; } = null!;
public virtual ICollection<Profile> Profiles { get; set; }
}
}
Run Code Online (Sandbox Code Playgroud)
配置文件.cs:
using System;
using System.Collections.Generic;
namespace MyApp.Models
{
public partial class Profile
{ …Run Code Online (Sandbox Code Playgroud)