c# - SQL 表未生成
问题描述
我正在尝试创建一个表,但架构似乎存在问题。请使用下面的代码,一切都在运行,直到外键。如果我注释掉 FOREIGN KEY,它会创建表,但使用外键会出现以下错误:
System.Data.SqlClient.SqlException:'无效的对象名称'产品'。
这是我的产品架构
public void CreateProductTable()
{
try
{
string tableName = "Products";
string schema = "ProductID int IDENTITY (1,1) PRIMARY KEY, " +
"ProductName VARCHAR(50) NOT NULL , " +
"ProductType VARCHAR(50) NOT NULL , " +
"ProductNumber int NOT NULL , " +
"ProductCondition VARCHAR(50) NOT NULL , " +
"ProductActiveInactive TINYINT NOT NULL , " +
"OnLoan BIT NOT NULL " +
"FOREIGN KEY(BrandID) REFERENCES ProductBrands(BrandID)";
Helper.CreateTable(tableName, schema);
}
catch (Exception e)
{
// Log errors
Console.WriteLine(e.Message);
}
}
这是我的 BrandProducts 架构:
public void CreateProductBrandTable()
{
try
{
string tableName = "ProductBrands";
string schema = "BrandID int IDENTITY (1,1) PRIMARY KEY, " +
"BrandName VARCHAR(50) NOT NULL";
Helper.CreateTable(tableName, schema);
}
catch (Exception e)
{
// Log errors
Console.WriteLine(e.Message);
}
}
Helper.CreateTable
public static void CreateTable(string tableName, string tableStructure)
{
string sql = $"CREATE TABLE {tableName} ({tableStructure})";
using (var connection = GetConnection())
{
try
{
connection.Execute(sql);
}
catch (Exception e)
{
Console.WriteLine(e);
}
}
}
获取连接:
public static bool DoTablesExist()
{
var connection = GetConnection();
string sql = $"SELECT COUNT(*) FROM {connection.Database}.INFORMATION_SCHEMA.TABLES" +
$" WHERE TABLE_TYPE = 'BASE TABLE'";
using (connection)
{
int number = connection.QuerySingle<int>(sql);
if (number > 0)
{
return true;
}
else
{
return false;
}
}
}
解决方案
您需要BrandId
产品表中的一列才能将其作为 FK 引用。虽然能够简单地编写FOREIGN KEY(x) REFERENCES(y)
并且 sql server 会创建与 Y 相同类型和大小的列 X 会很可爱,但它不起作用 - 要创建的列列表需要其中的 X/X 需要首先存在
在您尝试插入您的产品之前,请记住插入您的相关品牌记录;一个品牌必须首先存在,这样产品才能引用它
推荐阅读
- iis - 从 IIS 上的 YII2 应用程序中删除 web 文件夹
- carddav - 如何查询 CardDAV
- html - 固定标题使下拉导航栏不起作用
- c - 为什么 get(sen) 在此代码中不起作用?
- google-chrome-extension - 如何检测何时无法从带有 chrome 扩展名的 popup.js 访问网站
- firebase - Dart Firebase Firestore Atomic 注册
- r - 使用 lapply 运行函数时,如何在文本文件中逐行写入输出?
- java - 两人硬币游戏:动态规划中的最优序列追踪
- python - 使用 python 文件作为 cmd 命令
- ios - 当其中一个文本字段正在编辑时,如何向上移动包含文本字段的 stackView