我的任务是从DBML中找到特定列的类型和长度。
我想传递DbContext,Table Name和Column Name来返回我正在寻找的值。我发现以下类似的例子,但它没有返回任何东西:
http://www.codeproject.com/Articles/27392/Using-the-LINQ-ColumnAttribute-to-Get-Field-Length
但是,我可能会错误地实现这一点。对于obj
参数,我应该传入DataContext吗?我发现当我尝试加载info
(对象数组)时我什么都没得到......
public static int GetLengthLimit(object obj, string field)
{
int dblenint = 0; // default value = we can't determine the length
Type type = obj.GetType();
PropertyInfo prop = type.GetProperty(field);
// Find the Linq 'Column' attribute
// e.g. [Column(Storage="_FileName", DbType="NChar(256) NOT NULL", CanBeNull=false)]
object[] info = prop.GetCustomAttributes(typeof(ColumnAttribute), true);
// Assume there is just one
if (info.Length == 1)
{
ColumnAttribute ca = (ColumnAttribute)info[0];
string dbtype = ca.DbType;
if (dbtype.StartsWith("NChar") || dbtype.StartsWith("NVarChar") || dbtype.StartsWith("VarChar"))
{
int index1 = dbtype.IndexOf("(");
int index2 = dbtype.IndexOf(")");
string dblen = dbtype.Substring(index1 + 1, index2 - index1 - 1);
int.TryParse(dblen, out dblenint);
}
}
return dblenint;
}
不,你传递其中一个实体的实例。
我实际上会改变它,将Type
作为参数,而不是实例。
对于给定的实体,此方法将生成字符串字段长度的字典(LinqToSQL语法):
public static Dictionary<string, int> GetStrFieldsLen()
{
Dictionary<string, int> dicFieldLen = new Dictionary<string, int>();
var myEntity = new myEntity();
foreach(var m in myEntity.GetType().GetProperties())
{
var typeName = myEntity.GetType().GetProperty(m.Name).PropertyType;
int iLen = 0;
if (typeName == typeof(string))
{
var tv= (m.CustomAttributes).First().NamedArguments.ToArray()[0].TypedValue.ToString(); // Get DbType member
int idxStart = tv.LastIndexOf("(") + 1;
if (int.TryParse(tv.Substring(idxStart, tv.LastIndexOf(")") - idxStart), out iLen)==false)
iLen= int.MaxValue; // Field length is MAX
dicFieldLen.Add(m.Name, iLen);
}
}
return dicFieldLen ;
}