首页 > 解决方案 > 设计数据库,其中表的主键也是另一个表的外键

问题描述

我正在尝试找出设计数据库的最佳方法。我有 2 张桌子,Product并且Image.

产品

PId PRIMARY KEY IDENTITY(1, 1)
PName
PPrice

图片

PId PRIMARY KEY IDENTITY(1,1)
PImage1 
PImage2
FOREIGN KEY (PId) REFERENCES Product(PId)

目前我的数据库设计得很糟糕。因为我假设每当添加条目时Product,就在添加条目之后Image。该假设还假设为 生成的主键Image与为 生成的主键相同Product

然后在控制器代码中我有:

_context.Product.Add(Product); // Add the created product record to the database

await _context.SaveChangesAsync();

_context.Image.Add(imageRecord); // Add the created image record to the database.

await _context.SaveChangesAsync();

其中 和 分别ProductimageRecord以下模型类的对象:

public class Product
{
    public int ProductID { get; set; }
    public string ProductName { get; set; }
    public string ProductShortDesc { get; set; }
    public string ProductLongDesc { get; set; }
    public decimal ProductPrice { get; set; }
}

public class Image
{
    [ForeignKey("Product")]
    [Key]
    public int ProductID { get; set; }
    public byte[] ProductImage1 { get; set; }
    public byte[] ProductImage2 { get; set; }
    public byte[] ProductImage3 { get; set; }
}

当我开始从表中删除条目时,这开始失败,并且自动递增的主键值不再相同。

我怎样才能更好地设计它,以便我能够选择 的主键Product,然后将其用作 的主键Image

标签: sqlasp.netasp.net-core.net-corerazor-pages

解决方案


我建议将图片存储在服务器文件系统中。我还建议创建一个带有图片的表格。

public class Product
{
    [Key]
    public int ProductID { get; set; }
    public string ProductName { get; set; }
    public string ProductShortDesc { get; set; }
    public string ProductLongDesc { get; set; }
    public decimal ProductPrice { get; set; }

    public Icollection<Image> Images { get; set; }
}

public class Image
{        
    [Key]
    public int ImageId { get; set; }
    public int ProductId { get; set; }
    public stirng ImageName { get; set; }

    [ForeignKey("ProductID")]
    public Product Product { get; set; }
}

现在要获取一张图片,满足从 Images 表中对 PruductId 的请求就足够了。

将来,这将允许您轻松更改图像数量。它还将加速您的应用程序的工作,因为您不必解析图片。


推荐阅读