首页 > 解决方案 > 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;
        }
    }
}

标签: c#mysqlsql-serverdatabase

解决方案


您需要BrandId产品表中的一列才能将其作为 FK 引用。虽然能够简单地编写FOREIGN KEY(x) REFERENCES(y)并且 sql server 会创建与 Y 相同类型和大小的列 X 会很可爱,但它不起作用 - 要创建的列列表需要其中的 X/X 需要首先存在

在您尝试插入您的产品之前,请记住插入您的相关品牌记录;一个品牌必须首先存在,这样产品才能引用它


推荐阅读