有没有人知道为给定类自动生成数据库表的方法?我不是在寻找一个完整的持久层 - 我已经有了一个我正在使用的数据访问解决方案,但我突然要从大量的类中存储大量信息而且我真的不想创建所有这些表都是手工制作。例如,给定以下类:
class Foo
{
private string property1;
public string Property1
{
get { return property1; }
set { property1 = value; }
}
private int property2;
public int Property2
{
get { return property2; }
set { property2 = value; }
}
}
我希望以下SQL:
CREATE TABLE Foo
(
Property1 VARCHAR(500),
Property2 INT
)
我也想知道如何处理复杂的类型。例如,在之前引用的课程中,如果我们将其改为:
class Foo
{
private string property1;
public string Property1
{
get { return property1; }
set { property1 = value; }
}
private System.Management.ManagementObject property2;
public System.Management.ManagementObject Property2
{
get { return property2; }
set { property2 = value; }
}
}
我怎么能处理这个?
我看过尝试自己使用反射自动生成数据库脚本来枚举每个类的属性,但它很笨重,复杂的数据类型让我感到难过。
答案 0 :(得分:85)
现在已经很晚了,我只花了大约10分钟,所以它非常邋,,但它确实有效,并且会给你一个很好的跳跃点:
using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
namespace TableGenerator
{
class Program
{
static void Main(string[] args)
{
List<TableClass> tables = new List<TableClass>();
// Pass assembly name via argument
Assembly a = Assembly.LoadFile(args[0]);
Type[] types = a.GetTypes();
// Get Types in the assembly.
foreach (Type t in types)
{
TableClass tc = new TableClass(t);
tables.Add(tc);
}
// Create SQL for each table
foreach (TableClass table in tables)
{
Console.WriteLine(table.CreateTableScript());
Console.WriteLine();
}
// Total Hacked way to find FK relationships! Too lazy to fix right now
foreach (TableClass table in tables)
{
foreach (KeyValuePair<String, Type> field in table.Fields)
{
foreach (TableClass t2 in tables)
{
if (field.Value.Name == t2.ClassName)
{
// We have a FK Relationship!
Console.WriteLine("GO");
Console.WriteLine("ALTER TABLE " + table.ClassName + " WITH NOCHECK");
Console.WriteLine("ADD CONSTRAINT FK_" + field.Key + " FOREIGN KEY (" + field.Key + ") REFERENCES " + t2.ClassName + "(ID)");
Console.WriteLine("GO");
}
}
}
}
}
}
public class TableClass
{
private List<KeyValuePair<String, Type>> _fieldInfo = new List<KeyValuePair<String, Type>>();
private string _className = String.Empty;
private Dictionary<Type, String> dataMapper
{
get
{
// Add the rest of your CLR Types to SQL Types mapping here
Dictionary<Type, String> dataMapper = new Dictionary<Type, string>();
dataMapper.Add(typeof(int), "BIGINT");
dataMapper.Add(typeof(string), "NVARCHAR(500)");
dataMapper.Add(typeof(bool), "BIT");
dataMapper.Add(typeof(DateTime), "DATETIME");
dataMapper.Add(typeof(float), "FLOAT");
dataMapper.Add(typeof(decimal), "DECIMAL(18,0)");
dataMapper.Add(typeof(Guid), "UNIQUEIDENTIFIER");
return dataMapper;
}
}
public List<KeyValuePair<String, Type>> Fields
{
get { return this._fieldInfo; }
set { this._fieldInfo = value; }
}
public string ClassName
{
get { return this._className; }
set { this._className = value; }
}
public TableClass(Type t)
{
this._className = t.Name;
foreach (PropertyInfo p in t.GetProperties())
{
KeyValuePair<String, Type> field = new KeyValuePair<String, Type>(p.Name, p.PropertyType);
this.Fields.Add(field);
}
}
public string CreateTableScript()
{
System.Text.StringBuilder script = new StringBuilder();
script.AppendLine("CREATE TABLE " + this.ClassName);
script.AppendLine("(");
script.AppendLine("\t ID BIGINT,");
for (int i = 0; i < this.Fields.Count; i++)
{
KeyValuePair<String, Type> field = this.Fields[i];
if (dataMapper.ContainsKey(field.Value))
{
script.Append("\t " + field.Key + " " + dataMapper[field.Value]);
}
else
{
// Complex Type?
script.Append("\t " + field.Key + " BIGINT");
}
if (i != this.Fields.Count - 1)
{
script.Append(",");
}
script.Append(Environment.NewLine);
}
script.AppendLine(")");
return script.ToString();
}
}
}
我将这些类放在一个程序集中进行测试:
public class FakeDataClass
{
public int AnInt
{
get;
set;
}
public string AString
{
get;
set;
}
public float AFloat
{
get;
set;
}
public FKClass AFKReference
{
get;
set;
}
}
public class FKClass
{
public int AFKInt
{
get;
set;
}
}
它生成了以下SQL:
CREATE TABLE FakeDataClass
(
ID BIGINT,
AnInt BIGINT,
AString NVARCHAR(255),
AFloat FLOAT,
AFKReference BIGINT
)
CREATE TABLE FKClass
(
ID BIGINT,
AFKInt BIGINT
)
GO
ALTER TABLE FakeDataClass WITH NOCHECK
ADD CONSTRAINT FK_AFKReference FOREIGN KEY (AFKReference) REFERENCES FKClass(ID)
GO
进一步的想法......我会考虑在你的类中添加一个属性,如[SqlTable],这样它只会为你想要的类生成表。此外,这可以清理一吨,修复错误,优化(FK Checker是一个笑话)等等......只是为了让你开始。
答案 1 :(得分:13)
@Jonathan Holland
哇,我认为这是我见过的最原始的工作,放在StackOverflow帖子中。做得好。 但是,而不是将DDL语句构造为字符串,您绝对应该使用SQL 2005中引入的SQL Server Management Objects类。David Hayden有一篇名为Create Table in SQL Server 2005 Using C# and SQL Server Management Objects (SMO) - Code Generation的帖子,介绍了如何使用SMO创建表格。强类型对象使用以下方法轻而易举:
// Create new table, called TestTable
Table newTable = new Table(db, "TestTable");
和
// Create a PK Index for the table
Index index = new Index(newTable, "PK_TestTable");
index.IndexKeyType = IndexKeyType.DriPrimaryKey;
VanOrman,如果你使用SQL 2005,肯定会让SMO成为你解决方案的一部分。
答案 2 :(得分:4)
尝试http://createschema.codeplex.com/
对象的CreateSchema扩展方法它返回包含CREATE TABLE脚本的任何对象的字符串。
答案 3 :(得分:3)
我认为对于复杂的数据类型,你应该通过指定一个ToDB()方法来扩展它们,该方法拥有自己的实现来在DB中创建表,这样它就变成了自动递归。
答案 4 :(得分:2)
截至2016年(我认为),您可以使用Entity Framework 6 Code First从poco c#classes生成SQL模式,或使用Database First从sql生成c#代码。 Code First to DB walkthrough
答案 5 :(得分:1)
对于复杂类型,您可以递归地将您遇到的每个类型转换为它自己的表,然后尝试管理外键关系。
您可能还想预先指定哪些类将转换为表格或不转换为表格。对于要在数据库中反映而不会使架构膨胀的复杂数据,可以为其他类型提供一个或多个表。此示例使用多达4:
CREATE TABLE MiscTypes /* may have to include standard types as well */
( TypeID INT,
TypeName VARCHAR(...)
)
CREATE TABLE MiscProperties
( PropertyID INT,
DeclaringTypeID INT, /* FK to MiscTypes */
PropertyName VARCHAR(...),
ValueTypeID INT /* FK to MiscTypes */
)
CREATE TABLE MiscData
( ObjectID INT,
TypeID INT
)
CREATE TABLE MiscValues
( ObjectID INT, /* FK to MiscData*/
PropertyID INT,
Value VARCHAR(...)
)
答案 6 :(得分:1)
您可以在此处执行与C#类相反的数据库表: http://pureobjects.com/dbCode.aspx
答案 7 :(得分:0)
另外......也许你可以使用一些工具,如Visio(不确定Visio是否这样做,但我认为确实如此)将你的类反向工程为UML,然后使用UML生成DB Schema ......或者使用像http://www.tangiblearchitect.net/visual-studio/
这样的工具答案 8 :(得分:0)
我知道你正在寻找一个完整的持久层,但NHibernate的hbm2ddl任务可以做到这几乎就像一个单行。
有一个NAnt task可以调用它,这可能很有用。
答案 9 :(得分:0)
Subsonic也是另一种选择。我经常用它来生成映射到数据库的实体类。它有一个命令行实用程序,可以让您指定表,类型和许多其他有用的东西
答案 10 :(得分:0)
尝试DaoliteMappingTool for .net。它可以帮助您生成类。 下载表格Here
答案 11 :(得分:0)
有一个免费的应用程序,Schematrix从DB生成类,检查是否反过来:) http://www.schematrix.com/products/schemacoder/download.aspx