是否可以获得VARCHAR、CHAR等的最大列长度?
这里有一种避免接触数据库的方法:
- 使用Reflection,获取与有问题的列相对应的实体类的属性
- 然后,检索该属性的System.Data.Lin.Mapping.Column属性
- 然后,解析此属性的DbType属性(例如NVarChar(255)NOT NULL)以获取列长度
在纯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到sql,您需要将其重写为linq。
此处回答:
Linq到SQL-底层列长度
尽管我发现它更整洁:
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;
}