在 Visual Studio 中为表生成 C# 类代码
我的服务器浏览数据库文件中有多个表。我想为表生成类的自动代码,因此所有类及其属性、构造函数和 getter setter 方法都会自动生成。
请告诉我这样做的步骤。
I have multiple tables in my Server Explore database file. I want to generate auto code of Classes for tables, so all classes with their attributes, constructor and getter setter methods automatically generate.
Kindly tell me steps to do so.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
不是自动生成,但使用 sql 和 information_schema 输出类定义并不难,其中类以表命名,列映射到属性。从那里你可以让它生成创建、更新和删除(我喜欢在 SQL Server 2008 下使用合并来进行包/更新)。
一次做一个,主要是字符串连接。下面的内容应该让您开始......
剩下的留给读者作为练习,正如他们所说,主要是因为细节取决于您,您可以使用支持变量而不是自动属性,在属性中放置标准逻辑,使值类型可为空,在制作自己的代码生成器时,使其适合您的模式/样式/需求。
Not autogenerate, but it's not hard to use sql and information_schema to output a class definition, with the class named after the table and the columns being mappped to properties. From there you can have it generate create, updates and deletes (I like to use merge for crate/updates under SQL Server 2008).
Do them one at a time and it's mainly string concatination. The below should get you started....
The rest is left as an exercise for the reader as they say mainly because the details are up to you, instead of auto properties you could use backing variables, put standard logic in the properties, make the value types nullable, when making your own code generator, make it fit your patterns/styles/needs.
如果您使用实体框架,请检查本文的步骤:
从现有数据库生成 EF Code First 模型类
If you use Entity Framework check the steps this article:
Generating EF Code First model classes from an existing database
你可以尝试这样的事情...
创建一个名为 ModelCreator.cs 的主类来执行所有关键操作。该应用程序的入口点是“连接”和“创建”按钮单击事件。它将触发 CreateConnectionString() 方法,该方法基本上从用户获取输入并动态创建连接字符串
从数据库获取表名称、属性及其类型
主方法、CreateModelClassFiles
一旦调用此方法,它就会为您完成所有操作。
我希望它能帮助你......
you could try something like this...
Create one main class with the name ModelCreator.cs that does all the key operations. Entry point to this application is the Connect and Create button click event. It will fire a CreateConnectionString() method, which basically gets the input from the user and dynamically creates the connection string
Get Table Names, Attributes and their types from the database
Main Method, CreateModelClassFiles
Once this method is called, it does every thing for you.
i hope it will helps you....
我已经修改了上面的类并包含了所有缺少的方法
}
I have modified the class above and included all missing methods
}
我认为从表生成 cs 类的最简单方法是在数据库上查询,例如在 SQL Server 中,您可以使用此查询:
然后运行此查询并在 Visual Studio 中的新类中复制打印的结果文本
我希望对您有用,祝您
好运
i think the easiest way to generate cs class from table is query on your database , for example in SQL server you can use this query:
then Run this query and copy printed Result text in New Class in Visual Studio
i hope works for you
good luck