Automatic generation of EF entities and mappings from existing database schema

This is  a bunch of useful scripts for generating C# Entity Framework Code First POCOs from existing database schema.

First, let’s create T-SQL function for generating C# class for EF entity:


This function deliberately ignores certain columns, (Created On/By, Modified On/By). This properties are pushed to EntityBase class, which our POCO inherits from. All other columns in DB table will be mapped to corresponding C# type.

Next, let’s create T-SQL function for EF configuration (mapping class):


Now, let’s put it all together in one script:


All source code is available here

Simplest way to restore MSSQL Server database

Here’s a simplest way I found (so far) to restore a database in MS SQL Server. First part lists “logicalnames” from the backup that you want to restore. Modify the path so it points to the actual path where your backup file is:

RESTORE FILELISTONLY FROM DISK = N'C:\[path]\[db_name_backup].bak'
 GO

This shows LogicalName and PhysicalName of the data and log backup files, which have to be used in the following script:

RESTORE DATABASE [db_name]
 FROM DISK = N'C:\[path]\[db_name_backup].bak'
 WITH FILE = 1,
 MOVE N'[data_file_logical_name]' TO N'C:\[restored_db_path]\[data_file_name].mdf',
 MOVE N'[log_file_logical_name]' TO N'C:\[restored_db_path]\[log_file_name].ldf',
 NOUNLOAD,
 STATS = 10
 GO

That’s it. Pretty simple, isn’t it?

How to delete all stored procedures from MSSQL database using cursor

Here is a code for deleting all stored procedures in SQL Server database using cursor.

DECLARE @name varchar(500)
DECLARE @sql varchar(max)
SET @sql = ''

DECLARE cur CURSOR
      FOR SELECT [name] FROM sys.procedures
      OPEN cur

      FETCH NEXT FROM cur INTO @name
      WHILE @@fetch_status = 0
      BEGIN
			SET @sql = 'DROP PROC ' + @name
			PRINT @sql
			EXEC (@sql)			
            FETCH NEXT FROM cur INTO @name
      END
      CLOSE cur
      DEALLOCATE cur