Come si converte un datatable in un oggetto POCO in Asp.Net MVC?Come si converte un datatable in un oggetto POCO in Asp.Net MVC?
risposta
Passare ogni DataRow nel costruttore della classe (o utilizzare getter/setter) e tradurre ogni colonna nella proprietà corrispondente. Fai attenzione con le colonne nullable per estrarle correttamente.
@tvanfosson: perché devi sempre avere lo stesso idee come me, e digito 5 secondi più veloce di me :-) –
Posso controllare il tempo e leggere le menti. : -o – tvanfosson
Cosa viene modificato qui? Capisco che dovremmo controllare se qualsiasi valore nella riga è nullo prima di assegnarlo alle proprietà nella classe. Ma a cosa ti riferisci come modificato? – Josh
Una tabella di dati contiene in genere molte righe: si desidera convertire ogni riga in un'istanza di oggetto?
In tal caso, è possibile ad es. aggiungere un costruttore al vostro oggetto POCO che accetterà un DataRow
come parametro, e poi estrae i pezzi di quel DataRow
:
public YourPOCO(DataRow row)
{
this.Field1 = row["Field1"].ToString();
...
this.FieldN = Convert.ToInt32(row["FieldN"]);
}
e così via, e quindi chiamare quel costruttore su ciascuna delle righe nel DataTable.Rows
collezione:
List<YourPOCO> list = new List<YourPOCO>();
foreach(DataRow row in YourDataTable.Rows)
{
list.Add(new YourPOCO(row));
}
e si potrebbe quindi creare una vista ASP.NET MVC o vista parziale sulla base di questo tipo "YourPOCO" e utilizzare il modello "lista" per creare un elenco di istanze "YourPOCO" in una lista- come display.
Marc
Grazie per aver menzionato l'elenco
ho visto la tua altra domanda sull'utilizzo di un DataTable nel livello di accesso ai dati. Se restituisci POCO ad un certo punto è una buona idea lasciare che il tuo DAL restituisca POCO già.
Si utilizzerà SqlDataReader per riempire il POCO. Questo è più leggero. A volte è più semplice usare DataSet e DataTable per gli elenchi delle voci, ma se si trasformano le righe in POCOS con caratteri stroncati, comunque sono abbastanza sicuro che questa è la strada da percorrere.
vecchia questione, in ogni caso questo può essere utile per qualcuno:
private static T CreatePocoObject<T>(DataRow dr) where T : class, new()
{
try
{
T oClass = new T();
Type tClass = typeof (T);
MemberInfo[] methods = tClass.GetMethods();
ArrayList aMethods = new ArrayList();
object[] aoParam = new object[1];
//Get simple SET methods
foreach (MethodInfo method in methods)
{
if (method.DeclaringType == tClass && method.Name.StartsWith("set_"))
aMethods.Add(method);
}
//Invoke each set method with mapped value
for (int i = 0; i < aMethods.Count; i++)
{
try
{
MethodInfo mInvoke = (MethodInfo)aMethods[i];
//Remove "set_" from method name
string sColumn = mInvoke.Name.Remove(0, 4);
//If row contains value for method...
if (dr.Table.Columns.Contains(sColumn))
{
//Get the parameter (always one for a set property)
ParameterInfo[] api = mInvoke.GetParameters();
ParameterInfo pi = api[0];
//Convert value to parameter type
aoParam[0] = Convert.ChangeType(dr[sColumn], pi.ParameterType);
//Invoke the method
mInvoke.Invoke(oClass, aoParam);
}
}
catch
{
System.Diagnostics.Debug.Assert(false, "SetValuesToObject failed to set a value to an object");
}
}
return oClass;
}
catch
{
System.Diagnostics.Debug.Assert(false, "SetValuesToObject failed to create an object");
}
return null;
}
- 1. Come si converte un oggetto java.sql.Date in un GregorianCalendar?
- 2. Come si converte un oggetto datetime.date in datetime.datetime in python?
- 3. Come si converte un oggetto in CSV usando JavaScript?
- 4. Come si converte un oggetto JSONObject in classe?
- 5. Come si converte un colore in un pennello in XAML?
- 6. Come convertire un DataTable/DataSet in un oggetto ObjectDataSource
- 7. dateTime oggetto in ASP.NET MVC
- 8. Come posso convertire un DataTable in un oggetto dinamico?
- 9. Come esportare un oggetto GridView.DataSource in un datatable o dataset?
- 10. Come si converte un valore JSONB in booleano in Postgresql?
- 11. Come si costruisce un percorso senza ViewContext in ASP.NET MVC?
- 12. come unire due dati DataTable in un datatable visualizzare in una gridview in asp.net
- 13. Come si converte un nome di funzione in una stringa
- 14. Come si converte un IntStream Java 8 in un elenco?
- 15. Come si converte un riferimento enum in un numero?
- 16. Come si converte un numero in un INTERVALLO di minuti?
- 17. Come si converte un numero intero in un tipo enumerato?
- 18. Come si converte un progetto xcode in un cocoapod?
- 19. Come si converte un dizionario in un ConcurrentDictionary?
- 20. ASP.NET MVC/EF4/POCO/Repository - Come aggiornare le relazioni?
- 21. Come si converte una stringa in un metodo di classe?
- 22. Come si converte un CString in doppio in C++?
- 23. Come si converte una stringa in un char * in C++?
- 24. Come si converte un InputStream in una stringa in Java?
- 25. Come si converte un oggetto array in una stringa in PowerShell?
- 26. Come si converte una stringa JSON in un oggetto JavaScript in jQuery?
- 27. Come si crea un oggetto longevo all'interno di IIS/ASP.Net?
- 28. Visualizzazione di DataTable standard in MVC
- 29. Consigli su POCO convalida con ASP.NET MVC/Entity Framework
- 30. Come si converte un System :: String^in const char *?
E 'per la visualizzazione in asp.net MVC. Per favore vedi questa domanda ... http://stackoverflow.com/questions/1353966/datatable-instead-of-entity-framework-in-asp-net-mvc – Josh