lunedì 4 luglio 2011

Generic Data Adapter

Questo post propone una soluzione alternativa qui :how to datatable to list solved



Ancora una volta estendo qualcosa che ho già realizzato, ma questa volta credo di essere arrivato, a quello che si può definire limite ( un limite è solo un confine che si supererà più avanti ).

Posto un contesto di Entity e Relations dove
l'entity è un classe che mappa gli attributi di una tabella,
l'entitiesCollection è una lista generica di entity,
l'adapter è l'oggetto che si connette ai dati.

using System;
using System.Collections.Generic;
using System.Reflection;
using System.Linq;
using System.Text;
using Commons;

namespace DataFactory.Generic
{

public static class GenericManager<I, L, A>
{
public static void Insert(I i)
{
Type t = typeof(A);
object a = Activator.CreateInstance(t);
t.InvokeMember("Insert",
BindingFlags.InvokeMethod,
null,
a,
new object[]{i});
}

public static void Update(I i)
{
Type t = typeof(A);
object a = Activator.CreateInstance(t);
t.InvokeMember("Update",
BindingFlags.InvokeMethod,
null,
a,
new object[] { i });
}

public static void Delete(I i)
{
Type t = typeof(A);
object a = Activator.CreateInstance(t);
t.InvokeMember("Delete",
BindingFlags.InvokeMethod,
null,
a,
new object[] { i });
}

public static L Select()
{
Type tL = typeof(L);
object ls = Activator.CreateInstance(tL);

Type tA = typeof(A);
object a = Activator.CreateInstance(tA);

tL.InvokeMember("AddRange",
BindingFlags.InvokeMethod,
null,
ls,
new object[]{
tA.InvokeMember("Select",
BindingFlags.InvokeMethod,
null,
a,
null)
}
);

return (L)ls;
}

public static L Select(string filter)
{
Type tL = typeof(L);
object ls = Activator.CreateInstance(tL);

Type tA = typeof(A);
object a = Activator.CreateInstance(tA);

tL.InvokeMember("AddRange",
BindingFlags.InvokeMethod,
null,
ls,
new object[] {
tA.InvokeMember("Select",
BindingFlags.InvokeMethod,
null,
a,
new object[] {filter}) }
);

return (L)ls;
}
}
}

1 commento:

Anonimo ha detto...

Interessante... non sono convinto che utilizzare generic paghi così tanto, però prima lo provo e poi magari ci ragiono su...

Grazie per il post!