How can I generate database tables from C# classes?

前端 未结 12 1449
谎友^
谎友^ 2020-12-02 05:26

Does anyone know a way to auto-generate database tables for a given class? I\'m not looking for an entire persistence layer - I already have a data access solution I\'m usi

12条回答
  •  时光取名叫无心
    2020-12-02 06:23

    @Jonathan Holland

    Wow, I think that's the most raw work I've ever seen put into a StackOverflow post. Well done. However, instead of constructing DDL statements as strings, you should definitely use the SQL Server Management Objects classes introduced with SQL 2005.

    David Hayden has a post entitled Create Table in SQL Server 2005 Using C# and SQL Server Management Objects (SMO) - Code Generation that walks through how to create a table using SMO. The strongly-typed objects make it a breeze with methods like:

    // Create new table, called TestTable
    Table newTable = new Table(db, "TestTable");
    

    and

    // Create a PK Index for the table
    Index index = new Index(newTable, "PK_TestTable");
    index.IndexKeyType = IndexKeyType.DriPrimaryKey;
    

    VanOrman, if you're using SQL 2005, definitely make SMO part of your solution.

提交回复
热议问题