简体   繁体   English

实体框架 - 获取SQL Server字段数据类型

[英]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 data type of a column in a table that I have created and entity for. 我是SQL Server的新手,并试图弄清楚是否有办法在我创建的表和实体中获取列的数据类型。

For example, if I have a SQL Server table 'Employees' with the following column 例如,如果我有一个带有以下列的SQL Server表'Employees'

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

Is there a way to find the data type for the empName field in C# / Entity Framework? 有没有办法在C#/ Entity Framework中找到empName字段的数据类型?

In the end what I am trying to see is the data type and the column length. 最后我要看的是数据类型和列长度。 So, if I were looping through all of the fields in the table/entity I would like to see: "varchar(255)", "varchar(100)", "int" etc. 所以,如果我循环遍历表/实体中的所有字段,我希望看到:“varchar(255)”,“varchar(100)”,“int”等。

You could either create a stored procedure and call that from EF passing in the table names, or run a raw sql command something like the following: 您可以创建一个存储过程并从EF中传入表名称,或者运行如下所示的原始sql命令:

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 field info from. ...其中myTableName是要从中返回字段信息的表的名称。

Do note that a -1 is returned if you are using an nvarchar(MAX) or varchar(MAX) and I'm sure there may be some other anomalies as I have not tested all types. 请注意,如果您使用的是nvarchar(MAX)varchar(MAX) ,则返回-1,并且我确定可能存在其他异常,因为我没有测试所有类型。

Also I have not tested the c# above, so it may need a tweak to work, but the principle is good and would benefit from being encapsulated in a nice method ;-) 另外我还没有测试过上面的c#,所以它可能需要调整才能工作,但原理很好,并且可以通过封装在一个很好的方法中受益;-)

For more info on running raw sql in EF see https://msdn.microsoft.com/en-us/data/jj592907.aspx 有关在EF中运行原始sql的更多信息,请参阅https://msdn.microsoft.com/en-us/data/jj592907.aspx

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM