0

I'm not experienced in SQL. I have two tables in my .net core project; categories and products. Obviously, there's a one-to-many relationship between the tables. I know the best way to connect the tables is to use a foreign key. a property like CategoryId in products with reference to Id in Categories table. But this project is being created for a third party company. I have to define an admin panel in the website, so they can add or modify products and categories. Is there any way to connect the two tables through a property like CategoryName. I mean there's a drop-down menu for them to choose the category while adding a product.

public class Category : BaseClass
    {
        public string CategoryName { get; set; }
        [NotMapped]
        public IFormFile Picture { get; set; }
        public List<Product> Products { get; set; }
    }

public class Product : BaseClass
    {
        public string ProductName { get; set; }
        [NotMapped]
        public string Description { get; set; }
        public double Price { get; set; }
        public int Quantity { get; set; }
        [NotMapped]
        public IFormFile Picture { get; set; }
        public string DescriptionFileName { get; set; }
        public Category Category { get; set; }

    }
 
  • `[NotMapped] public IFormFile Picture` - I would highly recommend to avoid using same classes to represent both the entities and the models for web methods (actions, minimal API hadlers, etc). – Guru Stron Feb 18 '23 at 08:36
  • This is already answered here: https://stackoverflow.com/a/21405245/13359090 – EspressoCode Feb 18 '23 at 08:37
  • Does this answer your question? [Add Foreign Key to existing table](https://stackoverflow.com/questions/10028214/add-foreign-key-to-existing-table) – EspressoCode Feb 18 '23 at 08:37
  • _"Is there any way to connect the two tables through a property like CategoryName"_ - I'm sure there is but it is not needed. Dropdowns usually support ability to show one value and post another, i.e. you show `CategoryName` as dropdown item display name and post `CategoryId` as selected value. – Guru Stron Feb 18 '23 at 08:38
  • You are talking cross purposes here: foreign keys are there to ensure referential integrity and ORMs can use them to understand how entities are linked. What you need here is a join that populates the drop down with names, but I'm sure your ORM can do this join for you. – Shadow Feb 18 '23 at 08:38
  • 2
    @EspressoCode I would argue that the question is not about adding foreign key. – Guru Stron Feb 18 '23 at 08:38
  • @GuruStron I think that'd be the answer, but how? Would you tell me more about the implementation? – amin khosravi Feb 18 '23 at 08:46
  • @aminkhosravi it depends on framework used for UI and actual code. – Guru Stron Feb 18 '23 at 08:48
  • @aminkhosravi see the answers to the duplicate question – Shadow Feb 18 '23 at 08:59

0 Answers0