是否可以获得VARCHAR,CHAR等的最大列长度?
答案 0 :(得分:4)
这是一种避免触及数据库的方法:
答案 1 :(得分:1)
在纯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。
答案 2 :(得分:1)
在这里回答:
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");
有人可以想到强烈输入字段引用的方法吗?
答案 3 :(得分:1)
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;
}