sql - 设计数据库,其中表的主键也是另一个表的外键
问题描述
我正在尝试找出设计数据库的最佳方法。我有 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();
其中 和 分别Product
是imageRecord
以下模型类的对象:
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
?
解决方案
我建议将图片存储在服务器文件系统中。我还建议创建一个带有图片的表格。
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 的请求就足够了。
将来,这将允许您轻松更改图像数量。它还将加速您的应用程序的工作,因为您不必解析图片。
推荐阅读
- java - 使用括号中的 JSON 值查询 Apache Solr
- scala - 适应反应的目的是什么?
- r - 如何更改 export_summs (R) 中的 p 值星截止值
- apache-spark - 使用 Spark 和 Alluxio 管理 S3 的文件大小
- javascript - 是否可以从 HTML 网络资源刷新 Dynamics CRM 子网格?
- python - 想要找到具有最多素数除数的数字,但它一直打印最后输入的数字及其除数
- angular - http.get() 不返回 observable
- amazon-web-services - 为什么ecs-cli service up很久没有完成
- php - PHP在While循环中迭代数组的变量
- powershell - 在 PowerShell 中使用 Azure DevOps REST API 更新生成定义