【发布时间】:2008-11-04 14:19:37
【问题描述】:
是否可以获得 VARCHAR、CHAR 等的最大列长度?
【问题讨论】:
-
您想知道列的最大可能长度吗,例如varchar(1000) 为 1000 还是此列中值的最大长度?
标签: .net sql linq linq-to-sql
是否可以获得 VARCHAR、CHAR 等的最大列长度?
【问题讨论】:
标签: .net sql linq linq-to-sql
这是一种避免接触数据库的方法:
【讨论】:
在纯 T-SQL 中,您可以使用以下查询:
select max_length from sys.columns as c inner join sys.objects o on c.object_id = o.object_id where o.name = 'myTable' and c.name = 'myColumn'
对于 linq-to-sql,您需要将其重写为 linq。
【讨论】:
在这里回答:
Linq to SQL - Underlying Column Length
虽然我发现改变起来更整洁:
public static int GetLengthLimit(Type type, string field) //definition changed so we no longer need the object reference
//Type type = obj.GetType(); //comment this line
然后调用:
int i = GetLengthLimit(typeof(Pet), "Name");
有人能想出一种强类型字段引用的方法吗?
【讨论】:
public static int GetLengthLimit(Model.RIVFeedsEntities ent, string table, string field)
{
int maxLength = 0; // default value = we can't determine the length
// Connect to the meta data...
MetadataWorkspace mw = ent.MetadataWorkspace;
// Force a read of the model (just in case)...
// http://thedatafarm.com/blog/data-access/quick-trick-for-forcing-metadataworkspace-itemcollections-to-load/
var q = ent.Clients;
string n = q.ToTraceString();
// Get the items (tables, views, etc)...
var items = mw.GetItems<EntityType>(DataSpace.SSpace);
foreach (var i in items)
{
if (i.Name.Equals(table, StringComparison.CurrentCultureIgnoreCase))
{
// wrapped in try/catch for other data types that don't have a MaxLength...
try
{
string val = i.Properties[field].TypeUsage.Facets["MaxLength"].Value.ToString();
int.TryParse(val, out maxLength);
}
catch
{
maxLength = 0;
}
break;
}
}
return maxLength;
}
【讨论】: