Я использую подход code-first с Entity Framework. Часто в начале проекта я трачу время на настройку файлов классов для сопоставления с базой данных. Поэтому, чтобы сэкономить время, я подумал, что должен быть способ генерировать их из базы данных.
Я наткнулся на поток stackoverflow, который охватывал большую часть того, что я хотел
https://stackoverflow.com/questions/5873170/generate-class-from-database-table
Я изменил его так, чтобы он смотрел на внешние ключи и печатал эти ссылки. Обратите внимание, что этот скрипт предполагает, что имена ваших таблиц указаны в единственном числе. Пожалуйста, смотрите предыдущую историю для функции от единственного до множественного числа
USE [YOURDATABASE] GO declare @TableName sysname = ‘TABLENAME’ declare @Result varchar(max) = ‘public class ‘ + @TableName + ‘ {‘ select @Result = @Result + ‘ public ‘ + ColumnType + NullableSign + ‘ ‘ + ColumnName + ‘ { get; set; } ‘ from ( select replace(col.name, ‘ ‘, ‘_’) ColumnName, column_id ColumnId, case typ.name when ‘bigint’ then ‘long’ when ‘binary’ then ‘byte[]’ when ‘bit’ then ‘bool’ when ‘char’ then ‘string’ when ‘date’ then ‘DateTime’ when ‘datetime’ then ‘DateTime’ when ‘datetime2’ then ‘DateTime’ when ‘datetimeoffset’ then ‘DateTimeOffset’ when ‘decimal’ then ‘decimal’ when ‘float’ then ‘float’ when ‘image’ then ‘byte[]’ when ‘int’ then ‘int’ when ‘money’ then ‘decimal’ when ‘nchar’ then ‘string’ when ‘ntext’ then ‘string’ when ‘numeric’ then ‘decimal’ when ‘nvarchar’ then ‘string’ when ‘real’ then ‘double’ when ‘smalldatetime’ then ‘DateTime’ when ‘smallint’ then ‘short’ when ‘smallmoney’ then ‘decimal’ when ‘text’ then ‘string’ when ‘time’ then ‘TimeSpan’ when ‘timestamp’ then ‘DateTime’ when ‘tinyint’ then ‘byte’ when ‘uniqueidentifier’ then ‘Guid’ when ‘varbinary’ then ‘byte[]’ when ‘varchar’ then ‘string’ else ‘UNKNOWN_’ + typ.name end ColumnType, case when col.is_nullable = 1 and typ.name in (‘bigint’, ‘bit’, ‘date’, ‘datetime’, ‘datetime2’, ‘datetimeoffset’, ‘decimal’, ‘float’, ‘int’, ‘money’, ‘numeric’, ‘real’, ‘smalldatetime’, ‘smallint’, ‘smallmoney’, ‘time’, ‘tinyint’, ‘uniqueidentifier’) then ‘?’ else ‘’ end NullableSign from sys.columns col join sys.types typ on col.system_type_id = typ.system_type_id AND col.user_type_id = typ.user_type_id where object_id = object_id(@TableName) ) t order by ColumnId set @Result = @Result + ‘ ‘ DECLARE @ForeignResult nvarchar(max) = ‘’ SELECT @ForeignResult = @ForeignResult + ‘ public virtual ‘ + tab2.name + ‘ ‘ + tab2.name + ‘ { get; set; }’ FROM sys.foreign_key_columns fkc INNER JOIN sys.objects obj ON obj.object_id = fkc.constraint_object_id INNER JOIN sys.tables tab1 ON tab1.object_id = fkc.parent_object_id INNER JOIN sys.schemas sch ON tab1.schema_id = sch.schema_id INNER JOIN sys.columns col1 ON col1.column_id = parent_column_id AND col1.object_id = tab1.object_id INNER JOIN sys.tables tab2 ON tab2.object_id = fkc.referenced_object_id INNER JOIN sys.columns col2 ON col2.column_id = referenced_column_id AND col2.object_id = tab2.object_id WHERE tab1.name = @TableName SET @ForeignResult = @ForeignResult + ‘ ‘ — [ScriptIgnore(ApplyToOverrides = true)] select @ForeignResult = @ForeignResult + ‘ public virtual ICollection<’ + t.name + ‘> ‘ + [master].[dbo].[MakePlural](t.name) + + ‘ { get; set; }’ — , t.name as TableWithForeignKey, — fk.constraint_column_id as FK_PartNo, c.name as ForeignKeyColumn from sys.foreign_key_columns as fk inner join sys.tables as t on fk.parent_object_id = t.object_id inner join sys.columns as c on fk.parent_object_id = c.object_id and fk.parent_column_id = c.column_id where fk.referenced_object_id = (select object_id from sys.tables where name = @TableName) order by t.name, fk.constraint_column_id set @Result = @Result + @ForeignResult set @Result = @Result + ‘ }’ print @Result