【问题标题】:How to set a foreign key for a table in C#?如何在 C# 中为表设置外键?
【发布时间】:2015-05-29 01:47:32
【问题描述】:

我正在开发一个创建数据库并构建维度和事实表的程序。我在设置外键和约束时遇到问题。

这是我正在尝试做的实际 SQL:

 CREATE TABLE FactSalesOrders
  (ProductKey int NOT NULL REFERENCES DimProduct(ProductKey),
   CustomerKey int NOT NULL REFERENCES DimCustomer(CustomerKey),
   SalespersonKey int NOT NULL REFERENCES DimSalesperson(SalepersonKey),
   OrderDateKey int NOT NULL REFERENCES DimDate(DateKey),
   OrderNo int NOT NULL,
   ItemNo int Not NULL,
   Quantity int Not NULL,
   SalesAmount money NOT NULL,
   Cost money NOT NULL
        CONSTRAINT [PK_FactSalesOrders] PRIMARY KEY NONCLUSTERED
    (
        [ProductKey],[CustomerKey],[SalespersonKey],[OrderDateKey],[OrderNo],[ItemNo]
    )
  )

这是事实表:

    //Creating Fact Table
    Table factTable = new Table(myDatabase, "Fact Table");

        //Column One: Product Key
        Column ProductKey = new Column(factTable, "ProductKey", DataType.Int);
        ProductKey.Nullable = false;
        factTable.Columns.Add(ProductKey);

        //Column Two: Customer Key 
        Column CustomerKey = new Column(factTable, "CustomerKey", DataType.Int);
        CustomerKey.Nullable = false;
        factTable.Columns.Add(CustomerKey);

        //Column Three: Sales Person Key
        Column SalespersonKey = new Column(factTable, "SalespersonKey", DataType.Int);
        SalespersonKey.Nullable = false;
        factTable.Columns.Add(SalespersonKey);

        //Column Four: Order Date Key
        Column OrderDateKey = new Column(factTable, "OrderDateKey", DataType.Int);
        OrderDateKey.Nullable = false;
        factTable.Columns.Add(OrderDateKey);

        //Column Five: Order Number
        Column OrderNo = new Column(factTable, "OrderNo", DataType.Int);
        OrderNo.Nullable = false;
        factTable.Columns.Add(OrderNo);

        //Column Six: Item Number
        Column ItemNo = new Column(factTable, "ItemNo", DataType.Int);
        ItemNo.Nullable = false;
        factTable.Columns.Add(ItemNo);

        //Column Seven: Quantity
        Column Quantity = new Column(factTable, "Quantity", DataType.Int);
        Quantity.Nullable = false;
        factTable.Columns.Add(Quantity);

        //Column Eight: Sales Amount
        Column SalesAmount = new Column(factTable, "SalesAmount", DataType.Money);
        SalesAmount.Nullable = false;
        factTable.Columns.Add(SalesAmount);

        //Column Nine: Cost
        Column Cost = new Column(factTable, "Cost", DataType.Money);
        Cost.Nullable = false;
        factTable.Columns.Add(Cost);

    factTable.Create();

这是所有 C# 代码(注意:事实表在底部):

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.SqlServer.Management.Smo;
using System.Data.SqlClient;
using System.Data;

namespace Hillstar_Project
{



    class Program
    {



        static void Main(string[] args)
        {
            Server myServer = new Server(@"localhost");
            Boolean exit = false;
            while (exit == false)
            {
                Console.Write("Enter Name Of Data Warehouse: ");
                String NewDatabaseName = Console.ReadLine();

                SqlConnection myConnection = new SqlConnection("user id=app;" +
                                           "password=test;server=localhost;" +
                                           "Trusted_Connection=yes;" +
                                           "database=test; " +
                                           "connection timeout=30");

                try
                {
                    myConnection.Open();
                    Console.WriteLine("Successful Connection");
                    try
                    {
                        //DatabaseObjectCreation(myServer);

                        DataWarehouseCreation(myServer, NewDatabaseName);
                        Console.ReadLine();
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e.ToString());
                    }

                }
                catch (Exception e)
                {
                    Console.WriteLine(e.ToString());
                }

                Console.Write("Exit? (y/n): ");
                if (Console.ReadLine() == "y")
                {
                    exit = true;
                }
                else
                {
                    exit = false;
                }
            }


        }





        private static void DataWarehouseCreation(Server myServer, String NewDatabaseName)
        {
            //Drop the database if it exists
            if (myServer.Databases[NewDatabaseName] != null){
                Console.Write("Are you sure you want to override existing database? (y/n): ");
                if(Console.ReadLine() == "y"){
                    myServer.Databases[NewDatabaseName].Drop();
                }
                else{
                    Console.WriteLine("Database was not overwritten...");
                    return;
                }
                }


            //Create database
            Database myDatabase = new Database(myServer, NewDatabaseName);
            myDatabase.Create();




            //Creating DimProduct
            Table DimProduct = new Table(myDatabase, "DimProduct");

                //Column One: Product Key
                Column productKey = new Column(DimProduct, "ProductKey", DataType.Int);
                productKey.Nullable = false;
                DimProduct.Columns.Add(productKey);

                //Column Two: Product Alt Key
                Column productAltKey = new Column(DimProduct, "ProductAltKey", DataType.NVarChar(10));
                productAltKey.Nullable = false;
                DimProduct.Columns.Add(productAltKey);

                //Column Three: Product Name
                Column productName = new Column(DimProduct, "ProductName", DataType.NVarChar(50));
                productName.Nullable = true;
                DimProduct.Columns.Add(productName);

                //Column Four: Product Description
                Column productDescription = new Column(DimProduct, "ProductDescription", DataType.NVarChar(100));
                productDescription.Nullable = true;
                DimProduct.Columns.Add(productDescription);

                //Column Five: Product Catagory Name
                Column productCatagoryName = new Column(DimProduct, "ProductCatagoryName", DataType.NVarChar(50));
                productCatagoryName.Nullable = true;
                DimProduct.Columns.Add(productCatagoryName);

                //Primary Key
                Index primaryKeyIndex1 = new Index(DimProduct, "PK_DimProduct");
                primaryKeyIndex1.IndexKeyType = IndexKeyType.DriPrimaryKey;
                primaryKeyIndex1.IndexedColumns.Add(new IndexedColumn(primaryKeyIndex1, "productKey"));
                DimProduct.Indexes.Add(primaryKeyIndex1);

            DimProduct.Create();
            Console.WriteLine("DimProduct Table Created");


            //Creating DimCustomer
            Table DimCustomer = new Table(myDatabase, "DimCustomer");

                //Column One: Customer Key
                Column customerKey = new Column(DimCustomer, "CustomerKey", DataType.Int);
                productKey.Nullable = false;
                DimCustomer.Columns.Add(customerKey);

                //Column Two: Customer Alt Key
                Column customerAltKey = new Column(DimCustomer, "CustomerAltKey", DataType.NVarChar(10));
                productAltKey.Nullable = false;
                DimCustomer.Columns.Add(customerAltKey);

                //Column Three: Customer Name
                Column customerName = new Column(DimCustomer, "CustomerName", DataType.NVarChar(50));
                customerName.Nullable = true;
                DimCustomer.Columns.Add(customerName);

                //Column Four: Customer Email
                Column customerEmail = new Column(DimCustomer, "CustomerEmail", DataType.NVarChar(50));
                customerEmail.Nullable = true;
                DimCustomer.Columns.Add(customerEmail);

                //Column Five: Customer Geography Key
                Column customerGeographyKey = new Column(DimCustomer, "CustomerGeographyKey", DataType.Int);
                customerGeographyKey.Nullable = true;
                DimCustomer.Columns.Add(customerGeographyKey);

                //Primary Key
                Index primaryKeyIndex2 = new Index(DimCustomer, "PK_DimCustomer");
                primaryKeyIndex2.IndexKeyType = IndexKeyType.DriPrimaryKey;
                primaryKeyIndex2.IndexedColumns.Add(new IndexedColumn(primaryKeyIndex2, "customerKey"));
                DimCustomer.Indexes.Add(primaryKeyIndex2);

            DimCustomer.Create();
            Console.WriteLine("DimCustomer Table Created");

            //Creating DimSalesPerson
            Table DimSalesperson = new Table(myDatabase, "DimSalesperson");

                //Column One: Salesperson Key
                Column salespersonKey = new Column(DimSalesperson, "SalespersonKey", DataType.Int);
                salespersonKey.Nullable = false;
                DimSalesperson.Columns.Add(salespersonKey);

                //Column Two: Salesperson Alt Key
                Column salespersonAltKey = new Column(DimSalesperson, "SalespersonAltKey", DataType.NVarChar(10));
                salespersonAltKey.Nullable = false;
                DimSalesperson.Columns.Add(salespersonAltKey);

                //Column Three: Salesperson Name
                Column salespersonName = new Column(DimSalesperson, "SalespersonName", DataType.NVarChar(50));
                salespersonName.Nullable = true;
                DimSalesperson.Columns.Add(salespersonName);

                //Column Four: Store Name
                Column storeName = new Column(DimSalesperson, "StoreName", DataType.NVarChar(50));
                storeName.Nullable = true;
                DimSalesperson.Columns.Add(storeName);

                //Column Five: Store Geography Key
                Column storeGeographyKey = new Column(DimSalesperson, "StoreGeographyKey", DataType.Int);
                storeGeographyKey.Nullable = true;
                DimSalesperson.Columns.Add(storeGeographyKey);

                //Primary Key
                Index primaryKeyIndex3 = new Index(DimSalesperson, "PK_DimSalesperson");
                primaryKeyIndex3.IndexKeyType = IndexKeyType.DriPrimaryKey;
                primaryKeyIndex3.IndexedColumns.Add(new IndexedColumn(primaryKeyIndex3, "salespersonKey"));
                DimSalesperson.Indexes.Add(primaryKeyIndex3);

            DimSalesperson.Create();
            Console.WriteLine("DimSalesperson Table Created");

            //Creating DimDate
            Table DimDate = new Table(myDatabase, "DimDate");

                //Column One: Date Key
                Column dateKey = new Column(DimDate, "DateKey", DataType.Int);
                dateKey.Nullable = false;
                DimDate.Columns.Add(dateKey);

                //Column Two: Calendar Year
                Column calendarYear = new Column(DimDate, "CalendarYear", DataType.Int);
                calendarYear.Nullable = false;
                DimDate.Columns.Add(calendarYear);

                //Column Three: Calendar Quarter 
                Column calendarQuarter = new Column(DimDate, "Calendar Quarter", DataType.Int);
                calendarQuarter.Nullable = false;
                DimDate.Columns.Add(calendarQuarter);

                //Column Four: Month Of Year
                Column monthOfYear = new Column(DimDate, "MonthOfYear", DataType.Int);
                monthOfYear.Nullable = false;
                DimDate.Columns.Add(monthOfYear);

                //Column Five: Month Name
                Column monthName = new Column(DimDate, "MonthName", DataType.NVarChar(15));
                monthName.Nullable = false;
                DimDate.Columns.Add(monthName);

                //Column Six: Day Of Month
                Column dayOfMonth = new Column(DimDate, "DayOfMonth", DataType.Int);
                dayOfMonth.Nullable = false;
                DimDate.Columns.Add(dayOfMonth);

                //Column Seven: Day Of Week
                Column dayOfWeek = new Column(DimDate, "DayOfWeek", DataType.Int);
                dayOfWeek.Nullable = false;
                DimDate.Columns.Add(dayOfWeek);

                //Column Eight: Day Name
                Column dayName = new Column(DimDate, "DayName", DataType.NVarChar(15));
                dayName.Nullable = false;
                DimDate.Columns.Add(dayName);

                //Column Nine: Fiscal Year
                Column fiscalYear = new Column(DimDate, "FiscalYear", DataType.Int);
                fiscalYear.Nullable = false;
                DimDate.Columns.Add(fiscalYear);

                //Column Ten: Fiscal Quarter
                Column fiscalQuarter = new Column(DimDate, "FiscalQuarter", DataType.Int);
                fiscalQuarter.Nullable = false;
                DimDate.Columns.Add(fiscalQuarter);

                //Primary Key
                Index primaryKeyIndex4 = new Index(DimDate, "PK_DimDate");
                primaryKeyIndex4.IndexKeyType = IndexKeyType.DriPrimaryKey;
                primaryKeyIndex4.IndexedColumns.Add(new IndexedColumn(primaryKeyIndex4, "dateKey"));
                DimDate.Indexes.Add(primaryKeyIndex4);


            DimDate.Create();
            Console.WriteLine("DimDate Table Created");



            //Creating Fact Table
            Table factTable = new Table(myDatabase, "Fact Table");

            //Column One: Product Key
            Column ProductKey = new Column(factTable, "ProductKey", DataType.Int);
            ProductKey.Nullable = false;
            factTable.Columns.Add(ProductKey);

            //Column Two: Customer Key 
            Column CustomerKey = new Column(factTable, "CustomerKey", DataType.Int);
            CustomerKey.Nullable = false;
            factTable.Columns.Add(CustomerKey);

            //Column Three: Sales Person Key
            Column SalespersonKey = new Column(factTable, "SalespersonKey", DataType.Int);
            SalespersonKey.Nullable = false;
            factTable.Columns.Add(SalespersonKey);

            //Column Four: Order Date Key
            Column OrderDateKey = new Column(factTable, "OrderDateKey", DataType.Int);
            OrderDateKey.Nullable = false;
            factTable.Columns.Add(OrderDateKey);

            //Column Five: Order Number
            Column OrderNo = new Column(factTable, "OrderNo", DataType.Int);
            OrderNo.Nullable = false;
            factTable.Columns.Add(OrderNo);

            //Column Six: Item Number
            Column ItemNo = new Column(factTable, "ItemNo", DataType.Int);
            ItemNo.Nullable = false;
            factTable.Columns.Add(ItemNo);

            //Column Seven: Quantity
            Column Quantity = new Column(factTable, "Quantity", DataType.Int);
            Quantity.Nullable = false;
            factTable.Columns.Add(Quantity);

            //Column Eight: Sales Amount
            Column SalesAmount = new Column(factTable, "SalesAmount", DataType.Money);
            SalesAmount.Nullable = false;
            factTable.Columns.Add(SalesAmount);

            //Column Nine: Cost
            Column Cost = new Column(factTable, "Cost", DataType.Money);
            Cost.Nullable = false;
            factTable.Columns.Add(Cost);

            factTable.Create();
            Console.WriteLine("Fact Table Created");


            Console.WriteLine("Database Created");


        }   

    }
}

【问题讨论】:

  • 请删除所有不必要的代码,以便我们轻松查看您的问题并帮助您解决问题。
  • 我添加了需要帮助的代码的特定部分。谢谢。
  • 这是一个学校项目吗?如果没有,为什么不使用 EF6 或 7 或其他一些 ORM?如果是家庭作业,我希望你这部分快点结束。
  • 这是为了我的实习。这只是他们给我的一个小项目。我猜他们只是想看看我能有多足智多谋。

标签: c# sql database foreign-keys constraints


【解决方案1】:

创建外键约束并添加到子表中

 ForeignKeyConstraint fk = new ForeignKeyConstraint(
        "ForeignKey", objCustomer.Columns["CustomerID"], objOrder.Columns["CustomerID"]);
    objOrder.Constraints.Add(fk);

您可以使用以下链接作为参考。
Refer Link1 Refer Link2

【讨论】:

  • 我昨晚找到了这些文章并尝试了它们,但我无法让 ForeignKeyConstraint 类与我的代码一起使用。根据 msdn 文档,它有四个参数,第一个是数据集。我不确定我需要将什么传递给这个参数。谢谢。
猜你喜欢
  • 1970-01-01
  • 2018-12-07
  • 2019-02-15
  • 1970-01-01
  • 2018-11-12
  • 1970-01-01
  • 1970-01-01
  • 2022-01-12
  • 2018-07-08
相关资源
最近更新 更多