Entity Framework - Get SQL Server Field Data Type

I am new to SQL Server and trying to figure out if there is a way to get the column data type in the table I created and the entities for.

For example, if I have a SQL Server Employees table with the following column

employeeID int, empName varchar(255), empDept varchar(100) 

Is there a way to find the data type for empName field in C # / Entity Framework?

In the end, I'm trying to see the data type and column length. So, if I iterated over all the fields in a table / entity, I would like to see: "varchar (255)", "varchar (100)", "int", etc.

+6
source share
1 answer

You can create a stored procedure and call it from EF passing in the table names, or run the raw sql command:

 var sqlToRun = string.format(@"SELECT column_name as 'Column Name', data_type as 'Data Type', character_maximum_length as 'Max Length' FROM information_schema.columns WHERE table_name = '{0}'", myTableName); using (var context = new dbContext()) { var tableFieldDetails= context.SqlQuery(sqlToRun).ToList(); //do something with the tableFieldDetails collection } 

... where myTableName is the name of the table to return the field information from.

Note that -1 if you are using nvarchar(MAX) or varchar(MAX) , and I am sure there may be some other anomalies, since I have not tested all types.

Also, I have not tested C # above, so it may require tuning to work, but the principle is good and will benefit from encapsulation in a good method; -)

For more information on running raw sql in EF, see https://msdn.microsoft.com/en-us/data/jj592907.aspx

0
source

Source: https://habr.com/ru/post/989242/


All Articles