Ricavare le proprietà definite come chiavi di una classe Linq2Sql

Scritto da  Massimo Bonanni il venerdì 10 giugno 2011  •  Linguaggio: C#,VB   • Livello: 100


Analizzando gli attribributi delle proprietà di una classe generata dal designer di Linq to SQL è possibile ricavare quali di queste sono chiavi univoche.

VB.NET

Imports System.Data.Linq.Mapping
Imports System.Reflection
 
Public Function GetPropertyKey(ByVal entityType As Type) As IEnumerable(Of String)
  Dim retval As IEnumerable(Of String) = Nothing
  Try
    retval = From p In entityType.GetProperties() _
            Where p.GetCustomAttributes(GetType(ColumnAttribute), True).Count > 0 _
            AndAlso CType(p.GetCustomAttributes(GetType(ColumnAttribute), True).First(), ColumnAttribute).IsPrimaryKey _
            Select p.Name
  Catch ex As Exception
    retval = Nothing
  End Try
  Return retval
End Function

 

C#

using System.Data.Linq.Mapping;
using System.Reflection;
 
public IEnumerable<string> GetPropertyKey(Type entityType)
{
  IEnumerable<string> retval = null;
  try
  {
      retval = from p in entityType.GetProperties()
               where p.GetCustomAttributes(typeof(ColumnAttribute), true).Length > 0
               && ((ColumnAttribute)p.GetCustomAttributes(typeof(ColumnAttribute), true).First()).IsPrimaryKey
               select p.Name;
 
  }
  catch (Exception)
  {
      retval = null;
  }
  return retval;
}

 

 E' necessario referenziare l'assembly System.Data.Linq.


Tags: Linq

 
x