venerdì 22 febbraio 2013

Recuperare le Primary Key di una tabella utilizzando Linq to SQL

Di seguito vengono illustrati i passaggi per recuperare e utilizzare i nomi delle Primary Key da una generica Tabella Linq



Utilizzo una classe custom per mapparmi gli attributi che mi serve recuperare
public class TableModel
{
    public string tableName { getset; }
    public string tableDesc { getset; }
    public string DataContextTableName { getset; }
    public string[] DataKeyNames { getset; }
}
 
public static List<TableModel> GetTabelle()
{
    var Context = GetContext();
 
    var dbTables = Context.Mapping.GetTables();
 
 
    var t = (from ta in dbTables
                select new TableModel()
                {
                    tableName = ta.TableName,
                    tableDesc = ta.TableName.Replace("dbo."string.Empty),
                    DataContextTableName = ta.RowType.Name + "s",
                    DataKeyNames = GetPrimaryKey(ta.RowType.Type).ToArray<string>()
                }).ToList();
 
 
    return t;
}
Recupero le Primary key dalla tabella


public static List<string> GetPrimaryKey(Type T)
{
    PropertyInfo[] infos = T.GetProperties();
    List<string> PKProperty = new List<string>();
    foreach (PropertyInfo info in infos)
    {
        var column = info.GetCustomAttributes(false)
            .Where(x => x.GetType() == typeof(ColumnAttribute))
            .FirstOrDefault(x =>
            ((ColumnAttribute)x).IsPrimaryKey &&
            ((ColumnAttribute)x).DbType.Contains("NOT NULL"));
 
 
        if (column != null)
        {
            PKProperty.Add(((System.Reflection.MemberInfo)(info)).Name);
        }
    }
 
    if (PKProperty == null)
    {
        throw new NotSupportedException(
            T.ToString() + " has no Primary Key");
    }
    return PKProperty;
 
}
Utilizzo, ad esempio, delle primary key per l'attributo DataKeyNames di una griglia RadGrid alimentata con un LinqDataSource
this.rgTables.MasterTableView.DataKeyNames = ((List<TableModel>)(ViewState[ListTable]))
                    .Where(t => t.DataContextTableName == cb_tabelle.SelectedValue)
                    .FirstOrDefault().DataKeyNames;

Nessun commento:

Posta un commento