首页 > 解决方案 > 如何防止 EntityFramework Core 创建关系

问题描述

我正在制作一个商店项目。

我创建了一个产品类:

        public Guid Id { get; set; }
        public string Name { get; set; }
        public decimal Price { get; set; }
        public string Description { get; set; }
        public string PhotoUrl { get; set; }
        public int Quantity { get; set; }

和一个订单类:

        public Guid Id { get; set; }
        public List<Product> Products { get; set; }
        public decimal TotalPrice { get; set; }
        //address
        public string Street { get; set; }
        public string HouseNumber { get; set; }
        public string PostCode { get; set; }
        public string City { get; set; }
        public Order()
        {
            Products = new List<Product>();
        }

正如您在 Order.cs 中看到的,有一个产品列表,但实体框架总是在我的产品和订单之间设置关系,但我只想将产品添加到此列表中,而没有关系。作为回应,我想得到这样的东西

{
"id" :"someID",
"products": [
{
first product
},
{
second product
}]
}

等。我怎样才能防止创建 ef 关系并做简单的列表?或者我怎样才能建立许多产品与许多订单的关系?

标签: c#asp.netentity-frameworkentity-framework-core

解决方案


您可以将 NotMapped 属性添加到 Property:

...  
[NotMapped]
public List<Product> Products { get; set; }
...

您将需要导入 System.ComponentModel.DataAnnotations


推荐阅读