reverse engineer/create c# interface from sql server table - c#

does anyone know how of a tool where I can point to my sql server database and it reads the schema and generates c# interface classes from the tables?
for example - say I have a table called 'Customers' with a "Name" column, "Address" Column and a "Phone" column it would generate a ICustomer.cs file with string Name {get;set;} string Address {get;set;} and int Phone {get;set;}
I am using a 'incomplete' code generator and it does not generate these interfaces.

How about the Linq to Sql O/R Designer?

I don't know of a tool doing it, but I know for sure that you can do it yourself quite easily!
Set up a string containing the header of the class, and another with the footer.
Then, create a new text file named as your table.
Write the header into the file.
For the body, just write a loop reading your table, which extracts the names and types of the fields, and writes an interface with that info.
At the end, write the footer to the file.
There you go with your brand new interface!
(As interfaces are juste plain text files, it's really easy...)

You could use SQLMetal.exe to get part of the job done. IT sounds like you want an interface, but this will create concrete classes. It'd be a small task to find/replace class with interface, and modify the names.
C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\Bin\SqlMetal.exe or open a Visual Studio Command Prompt.
Usage: sqlmetal /server:myserver /database:myDB /user:myUser /pwd:myPwd /language:csharp /code:myDB.cs
More options over at the MSDN page for SQLMetal.

You need a tool that allows you to customize your code generation templates. Have you considered Enterprise Architect, or CodeSmith?
There are numerous others - you may even want to go for a Model Driven Architecture. Design your solution in UML and generate the database and the code from the UML model. You can use a combination of tools for this, for example MagicDraw and Maven.

I think I can use Resharpers 'Extract Interface' refactor as I have generated the class already.
Thanks for everyones input though

My SqlSharpener project lets you parse SQL files at design-time to create a meta-model which you can then use to generate any type of code you like in a T4 template. For example, you could create Entity Framework Code First entities.

You can also use MyGeneration

Related

What is the best practice to create SQL script files?

At work, we have multiple telegrams to communicate with a customer. Those telegrams are always different with each customer, but the logic, how we work with them is always the same. The data is sent to a table on our schema with other data for example like sent time and telegram type. We split it into a view to simplify it for development and testing purpose.
Example JSON:
{"Prop1": "Test"}
Example view script (using Oracle Enterprise):
CREATE OR REPLACE VIEW test
AS
SELECT prop1
FROM telegram
, JSON_TABLE (
telegram.json,
'$' COLUMNS (
prop1 PATH '$.Prop1'
)
)
My problem is now, that I do not know the correct or good way to create those view scripts with C#. Currently, I use a constant string with placeholders ({0}, {1}, ...) but they are getting really hard to maintain. I also read about T4, but it is only useable with Visual Studio. AFAIK we plan to move to .NET 5 and it looks like T4 is not available anymore and/or you cannot call the created C# classes in the code without some errors. I heard about Roslyn, too. Is it possible to create .txt/.sql instead of .cs files?
I hope I got all the information needed to answer this question. If I forgot some information, tell me. Thanks in advance!
Is it possible to create .txt/.sql instead of .cs files?
Sure, you can add the .txt/.sql file to your project and set its build action to "Embedded Resource".
In your code, you can access the content of that resource with Assembly.GetManifestResourceStream or by linking it to a resource file. Afterwards, you can apply String.Replace or String.Format for placeholders, if required.
That having been said, you might want to consider storing your data as relational data in your database, instead of JSON text that needs to be parsed by a for Every. Single. Query. Not only will this allow you to get rid of your view, but it will improve performance and allow you to use indexes on relevant fields.

Forcing Entity Framework generated classes to have Pascal casing and column names to have Camel casing

I have been working with Entity Framework 4 and SQL Server. The main problem I have found is that the table names in the database are all lower case and has underscore. This means that when I create the entities in Visual Studio, the classes and the properties are all lower case with underscores Is there any way to achieve Pascal Casing for the classes created and Camel Casing for the Properties?
Eg:
table_name--> to be converted as TableName
Is there any other templates need to be added or any other way to achieve this.
Editing the class name and properties manually in is not recommended as i have huge number of entities
Why not use a T4 template to generate the entity classes? That way, you can add a method to convert the table names to the convention of your choice.
VS comes with a couple of built-in T4 templates for EF, so it's very likely that you can just pick one of these and modify it. I wouldn't recommend writing your own from scratch!
If you haven't used T4 templates before, a quick start is to open your EF model in the designer, right-click a blank part of the design surface and choose "Add Code Generation Item." This will open a dialog with the installed T4 templates for EF, and you can choose whichever you feel most appropriate.
You can then right-click the T4 template files in Solution Explorer (it will have a .tt extension) and choose "Run Custom Tool" to generate the entities themselves. You can edit the .tt file (it's just a plain text file, containing something that looks horribly like VBScript!) and make the modifications. Then run the custom tool again and see if the generated entities have the right names.
Hope this helps.
The following blog post has a great response on how to do this. It involves modifying the T4 template file created when creating the data model.
http://khalidk7.wordpress.com/2014/04/21/entity-framework-ef-t4-template-modification-to-output-pascalcasing-database-objects/

Create SQL Server database tables from C# classes

Is it possible to automatically convert a lot of C# classes to SQL Server database tables ?
I need to import some xml files into SQL Server but using SSIS the runtime stops working as soon as I select the xsd file. However I easily converted the xsd to class files so that's why I am asking if its possible to have a workaround...
You can use Entity Framework Code First functionality, with a little extra work to get the tables done in your database.
There you have a good post on it by ScottGu
Yes, it's possible to automatically do this. Entity Framework has a model called Code First, which essentially does this: takes your C# classes and creates the database and tables automatically for you.
Take a look at this post by Scott Guthrie.
Other option you might test is DataSet.ReadXml() function. Drawback is the Dataset can't handle complexType="mixed", but it deals well with large files (my files had about 50M each). All tables and columns are named by XML tags and relations are autogenerated by DataSet itself.

How to auto-build custom commands in a DataSet based on non-"DELETE" deletion method?

I am using DataSets for access to Sql Server 200x in a C# project. Our common practice is, in almost all tables, to not delete the record. Instead we have a field which simply holds a bit for whether the record is deleted. I can manually edit each table in the DataSet and make their select command include Where Deleted = 0 and the delete command be an update instead. However, this is tedious.
Is there any way to change the method that VS uses to generate the commands for the tableadaptor to add this functionality for them automatically?
Edit:
In effect, this would be some sort of way to customize the GenerateDBDirectMethods functionality.
You could access your data through database views and do your filtering there.
Personally I do not like SQL commmands in DataSet definitions.
EDIT:
There is not a built-in possibility to do this AFAIK. You could make an VS add-in and invoke it on a context menu from Solution Explorer (right click on .xsd) or open DS and invoke add-in from main menu. The add in would then parse xsd and identify select and update text and make corrections. Probably this would be useful only right after generating the DS (drag drop from sql server).
For add.in look at:
Creating a Visual Studio.NET add-in to write SQL statements
Writing a Visual Studio 2005 & 2008 Add-In
Tutorial : Creating Visual Studio Add-Ins
I personally would go the DB way. Make views that do the filtering for you and add delete triggers on those views that would perform an update instead of delete. This way you are removing the burden to do that on application and make this the responsibility of the person that makes a physical DB model. This would be done once per table. On the contrary you probably have multiple points in code that deal with single table (multiple datasets that use the same db table).
I don't think you will be able to auto generate this using something like the SqlCommandBuilder.
Instead what you may be looking to do is utilize the fact that the strongly typed datasets and data adapters in the dataset auto generated code use partial classes and you should therefore be able to add some additional logic to a partial class which will override the default implementation.
For example you should be able to override the InitCommandCollection method on the generated data table adapter which you could then substitute in your Update isDeleted = 1, instead of the delete command.
You will have to write some smarts around this but it should help you. I would recommend having the table adapter check a list to see if the table name is within the list, if it is then you know you are dealing with a deleted column, if not then it's a deletable table record.
I would look at using a tool like CodeSmith and creating a custom template to create your Datasets rather then using the "drag + drop" designer. Creating a template takes longer in the first place, but gives your control and repeatability over what you create.
Otherwise look at one of the better ORM systems and customise it’s mapping to do what you want.

How do I use sqlmetal to generate an internal (not public) data context

I'd like to use sqlmetal to generate dbml data contexts for my project, but the data context and all classes created are marked as public. As this is supposed to be an API layer I'd like to instead mark many of these classes or at least the context itself as internal. Is there a way to do this in sqlmetal or some other tool without having to go in and edit the dbml by hand?
I believe this is one of the options that you can't do directly at the command line. You may indeed have to edit the dbml. However, this isn't a tricky change, so you should be able to automate it with a basic command-line tool.
You could try using my LINQ to SQL template that provides a drop-in replacement for the DBML to C#/VB.NET code generation process that you can completely customize.
[)amien

Categories

Resources