locked
Best Practice Advice RRS feed

  • Question

  • User1820827484 posted

    Hello Community, 

    I would like to have best practice advice in following scenario. 

    There is a database table called "Product" containing fields "Id,title,category" where "Category" is a foreign key.  

    In "Product" class , I can implement the same fields as "class attributes" . 

        public class Product
        {
            private int id;
            private string title;
           
            /*Foreign Key*/
            
            private int categoryId;
            
    
            public int ID
            {
                get { return id; }
                set { id = value; }
            }
            public string Title
            {
                get { return title; }
                set { title = value; }
            }
            
    
            
            public int CategoryId
            {
                get { return categoryId; }
                set { categoryId = value; }
            }
           
            // default constructor
    
            public Product() {
    
         
            
            }
    
    
    
    
        }
    
    

    Is this right approach to make "categoryId" part of Product class and fill this attribute value with Category DTO class from Presentation layer?

    Saturday, October 11, 2014 5:04 PM

Answers

  • User-821857111 posted

    You need to separate in your ow n mind how to design tables in a database and how to design classes. They are not the same thing. You need to think about foreign keys in database-design mode, because that's how databases work. There is no such thing as a foreign key anywhere else in the Universe apart from in a database. 

    When designing objects, you look at relationships in a different way. A product has a category, so a class that represents a product must include a Category property:

    public class Product
    {
        public int ID {get;set;}
        public string Title {get;set;}
        public Category Category  {get;set;}
    }



    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Saturday, October 11, 2014 5:58 PM