【问题标题】:Obtain max length for a "string" column using LINQ to SQL使用 LINQ to SQL 获取“字符串”列的最大长度
【发布时间】:2008-11-04 14:19:37
【问题描述】:

是否可以获得 VARCHAR、CHAR 等的最大列长度?

【问题讨论】:

  • 您想知道列的最大可能长度吗,例如varchar(1000) 为 1000 还是此列中值的最大长度?

标签: .net sql linq linq-to-sql


【解决方案1】:

这是一种避免接触数据库的方法:

  • 使用反射,获取对应列的实体类的属性。
  • 然后,检索属性的 System.Data.Linq.Mapping.Column 属性。
  • 然后,解析该属性的 DbType 属性(例如 NVarChar(255) NOT NULL)以获取列长度。

【讨论】:

    【解决方案2】:

    在纯 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。

    【讨论】:

      【解决方案3】:

      在这里回答:

      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");
      

      有人能想出一种强类型字段引用的方法吗?

      【讨论】:

        【解决方案4】:
        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;
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2016-03-25
          • 2017-10-26
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多