locked
Why does EntityFrameworkCore generate navigation property if there is no foreign key? RRS feed

  • Question

  • User1725160972 posted
    I have a such table schema:
    CREATE TABLE Categories
    (
        Id INT IDENTITY(1,1),
        Name varchar(100),
        CONSTRAINT PK_Category_Id PRIMARY KEY (Id)
    )
    
    CREATE TABLE Products
    (
        Id INT IDENTITY(1,1),
        IdCategory INT NOT NULL
            CONSTRAINT FK_Products_IdCategory__Categories_Id FOREIGN KEY(IdCategory) REFERENCES Categories(Id),
        Name varchar(100), 
        Price decimal(18,2),
        ImageUrl varchar(256),
        CONSTRAINT PK_Product_Id PRIMARY KEY (Id)
    )

    I execute the following command in the Package Manager Console:

    Scaffold-DbContext "Server=FOO-PC\SQL2014XP;Database=fooDatabase;Trusted_Connection=True;" 
        Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models

    Entity Framework Core generates the following domain classes:

    public partial class Categories
    {
        public Categories()
        {
            Products = new HashSet<Products>();
        }
    
        public int Id { get; set; }
        public string Name { get; set; }
    
        public virtual ICollection<Products> Products { get; set; }
    }
    
    public partial class Products
    {
        public Products()
        {
            OrderItems = new HashSet<OrderItems>();
            ShoppingCartItems = new HashSet<ShoppingCartItems>();
        }
    
        public int Id { get; set; }
        public int IdCategory { get; set; }
        public string Name { get; set; }
        public decimal? Price { get; set; }
        public string ImageUrl { get; set; }
    
        public virtual Categories IdCategoryNavigation { get; set; }
        public virtual ICollection<Items> Items { get; set; }        
    }

    My question are:

    1. Why does EF Core generates public virtual ICollection<Products> Products { get; set; } in Categories class?
    2. Is it possible to prevent generation this property Products?
    Saturday, September 21, 2019 9:05 PM

Answers

  • User475983607 posted

    Your SQL DDL specifically sets a foreign key constraint which resolves to a navigation property in EF.

    IdCategory INT NOT NULL
    CONSTRAINT FK_Products_IdCategory__Categories_Id FOREIGN KEY(IdCategory) REFERENCES Categories(Id),

    Why does EF Core generates public virtual ICollection<Products> Products { get; set; } in Categories class?

    As written, one category can have many products.  

    Is it possible to prevent generation this property Products?

    Remove the foreign key constraint but doing so does not make sense.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Sunday, September 22, 2019 11:35 AM