简体   繁体   中英

How to prevent creating relations by EntityFramework Core

I am making a school project which is a shop.

I have created a Product class:

        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; }

and an Order class:

        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>();
        }

As you see in Order.cs there is a list of Products, but entity framework always sets a relationship between my product and a order but I just want to add a Product to this list with no relation ship. As a response I want to get something like this

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

etc. How can I prevent creating by ef relationships and do simple lists? Or how can I do a relationship many products to many orders?

You can add the NotMapped attribute to the Property:

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

You will need to import System.ComponentModel.DataAnnotations

Either I'm missing something, or you are trying to do something that doesn't make much sense. You say there is no relation - but you do want to save both Order and it's Products to the database? That means that there IS relation (of 1:N kind) and EF is right to create it. It can't work without it.

You didn't include full output that you expect, only the Order part with first_product and second_product placeholders. If the placeholders look like your Product class, just let EF create the relation and you are done. If you want them to look different in JSON (omit some properties for example), you should still let EF create the relation, and then write transformation from your Entity classes (Product, Order) to DTO classes (ProductDTO, and OrderDTO that has List<ProductDto> ). Which is good practice anyway, even if Entity and DTO match 1:1, in real project it rarely stays that way for long.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM