簡體   English   中英

如何在 ASP.NET Core 6 Web API 中使用一對一關系將外鍵添加到表中?

[英]How to add a foreign key into a table using one-to-one relationship in ASP.NET Core 6 Web API?

我是 ASP.NET 的新手,如何讓我的item表保存從categoryID表中獲取的category ID? 例如,我希望“Apple 手機”商品具有類別 ID,該類別 ID 指的是電子產品的類別名稱,希望您能得到圖片。

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

這是我的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");
        }
    }
}

我嘗試了所有可能的方法,但總是有問題,多個項目可能屬於同一類別,例如手機品牌項目都在“電子”類別下

您可以通過以下方式配置兩個實體之間的一對一關系:

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

    }

注意:C# 最好使用 PascalCase

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM