2008-11-04 13 views

Odpowiedz

1

W czystej T-SQL można użyć tej kwerendy:

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' 

Dla LINQ-SQL trzeba go przepisać do LINQ.

4

Oto sposób, który pozwala uniknąć dotykania bazie danych:

  • użyciu odbicia, uzyskać właściwość klasy podmiotu, który odpowiada danej kolumny.
  • Następnie pobierz atrybut System.Data.Linq.Mapping.Column dla właściwości.
  • Następnie przeanalizuj właściwość DbType tego atrybutu (np. NVarChar (255) NOT NULL), aby uzyskać długość kolumny.
1

tutaj odpowiedzi:

Linq to SQL - Underlying Column Length

Choć uważam, że to neater zmienić:

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 

i wezwać za pomocą:

int i = GetLengthLimit(typeof(Pet), "Name"); 

ktoś może myśleć o od sposób silnego pisania odniesienie do pola?

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; 
} 
Powiązane problemy