Ricavare la tabella di database a cui è collegata una classe Linq2Sql
Scritto da
Massimo Bonanni il
martedì 17 maggio 2011
•
Linguaggio:
• Livello: 100
Le classi generate dal designer di Linq To SQL sono decorate con
l'attributo TableAttribute in cui è indicata la
tabella della banca dati SQL a cui la classe è
collegata. E' possibile recuperare, da codice, il nome della
tabella andando a leggere il valore
dell'attributo.
VB.NET
Imports System.Data.Linq.Mapping
Public Function GetEntityTable(ByVal entityType As Type) As String
Dim retval As String = Nothing
Try
Dim attrib = CType(entityType.GetCustomAttributes(GetType(TableAttribute), True).FirstOrDefault(), TableAttribute)
If attrib IsNot Nothing Then
retval = attrib.Name
End If
Catch ex As Exception
retval = Nothing
End Try
Return retval
End Function
C#
using System.Data.Linq.Mapping;
public string GetEntityTable(Type entityType)
{
string retval = null;
try
{
TableAttribute attrib = (TableAttribute)entityType.GetCustomAttributes(typeof(TableAttribute), true).FirstOrDefault<object>();
if (attrib != null)
{
retval = attrib.Name;
}
}
catch (Exception)
{
retval = null;
}
return retval;
}
E' necessario referenziare l'assembly
System.Data.Linq.
Tags: Linq,linq to sql,linq to sql server