1

I am new to ASP.NET, how can I make my item table save the categoryID which I get from the category table? As an example I want the item "Apple mobile phone" to have the category ID which refers to category name which is electronics, I hope you got the picture.

Here is model:

using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace WebApplication1.Models
{
    public class itemTable
    {
        [Key]
        public int Id { get; set; }

        public string company { get; set; }
        public string availability { get; set; }

        public decimal price { get; set; }
        public decimal discount { get; set; }
        public decimal tax { get; set; }

        public string description { get; set; }

        public int categoryid { get; set; }
    }

    public class categories
    {
        [Key]
        public int categoryID { get; set; }

        public string categoryName { get; set; }
    }
}

And here is my DbContext:

using Microsoft.EntityFrameworkCore;
using System.Diagnostics;
using WebApplication1.Models;

namespace WebApplication1.Context
{
    public class itemTableDbContext : DbContext
    {
        public itemTableDbContext(DbContextOptions options) : base(options)
        {
        }

        public DbSet<itemTable> ItemTables { get; set; }
        public DbSet<categories> categories { get; set; }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<itemTable>().ToTable("itemtable");
            modelBuilder.Entity<categories>().ToTable("categories");
        }
    }
}

I tried all the possible ways but there is always something wrong, multiple items might be in the same category like phone brand items are all under the "electronics" category

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459

1 Answers1

0

You can configure One-to-One relationship between two entities in such way:

    public class ItemTable
    {
        [Key]
        public int Id { get; set; }

        public string Company { get; set; }

        public string Availability { get; set; }

        public decimal Price { get; set; }

        public decimal Discount { get; set; }

        public decimal Tax { get; set; }

        public string Description { get; set; }

        public virtual Category Category { get; set; }

    }

    public class Category
    {
        [Key]
        [ForeignKey("ItemTable")]

        public int CategoryID { get; set; }

        public string CategoryName { get; set; }

        public virtual ItemTable ItemTable { get; set; }    

    }

Note: Better to use PascalCase in C#

Nika
  • 379
  • 2
  • 16