首页 > 解决方案 > 如何在返回的 JSON 中不显示外键 ID?

问题描述

我正在使用 .NET Core 3.0 Web API 项目。在建立关系时,我有一个名为的模型属性ProductTypeID,它是一个保存表 ID 的外键ProductType。当我查询UnitOfWork并将这个结果返回给控制器时,我希望productTypeID从 JSON 中删除。

产品控制器:

[HttpGet]
public IEnumerable<Product> Index()
{
    var products = _service.GetAll();

    return products;
}

存储库(它最终返回数据,返回服务然后返回控制器):

public override IEnumerable<Product> GetAll()
{
    return _context.products
        .Include(x => x.ProductType)
        .AsEnumerable();
}

产品播种机:

_modelBuilder.Entity<ProductType>().HasData(new ProductType
{
    ID = 1,
    Name = "Pizza"
});

_modelBuilder.Entity<Product>(x =>
{
    x.HasOne(d => d.ProductType)
    .WithMany()
    .HasForeignKey(p => p.ProductTypeID);
});

_modelBuilder.Entity<Product>().HasData(
    new Product { 
        ProductTypeID = 1,
        ID = 1,
        Name = "Pepperoni",
        Price = 12m,
        Description = "Test Description"
    },
    new Product
    {
        ProductTypeID = 1,
        ID = 2,
        Name = "Margherita",
        Price = 10m,
        Description = "This is a margherita pizza"
    }
);

产品型号:

public class Product : BaseModel
{
    [Required]
    public string Name { get; set; }

    [Required]
    [Column(TypeName = "decimal(18,2)")]
    public decimal Price { get; set; }

    [Required]
    public string Description { get; set; }

    public int ProductTypeID { get; set; }


    public virtual ProductType ProductType { get; set; }
}

在浏览器上返回 JSON:

[
  {
    "name": "Pepperoni",
    "price": 12,
    "description": "Test Description",
    "productTypeID": 1,
    "productType": {
      "name": "Pizza",
      "id": 1,
      "createdAt": "20/01/2020 19:28:26",
      "updatedAt": "20/01/2020 19:28:26"
    },
    "id": 1,
    "createdAt": "20/01/2020 19:28:26",
    "updatedAt": "20/01/2020 19:28:26"
  },
  {
    "name": "Margherita",
    "price": 10,
    "description": "This is a margherita pizza",
    "productTypeID": 1,
    "productType": {
      "name": "Pizza",
      "id": 1,
      "createdAt": "20/01/2020 19:28:26",
      "updatedAt": "20/01/2020 19:28:26"
    },
    "id": 2,
    "createdAt": "20/01/2020 19:28:26",
    "updatedAt": "20/01/2020 19:28:26"
  }
]

我相信如果我创建一个ViewModel并只返回我需要的属性,这将起作用。但我想知道是否有一种方法可以在不创建ViewModel.

标签: jsonasp.net-web-apiasp.net-core-webapi

解决方案


您可以添加JsonIgnore属性以productTypeID从 JSON 中删除:

public class Product:BaseModel
{
    [Required]
    public string Name { get; set; }
    [Required]
    [Column(TypeName = "decimal(18,2)")]
    public decimal Price { get; set; }
    [Required]
    public string Description { get; set; }

    [JsonIgnore]
    public int ProductTypeID { get; set; }

    public virtual ProductType ProductType { get; set; }
}

推荐阅读