C# Db Class GeneratorAuthor: Dave Date: 10.10.12 - 8:28am Download: DbClassGen.zip Needed this for a small project so thought i would share. Sometimes you want to generate C# classes that mirror the data types used in a database table. You also want an easy way to load all of the class members from a data base record. This is a nice way to access members because you get intellisense when accessing them, and dont have to manually cast everything from the data reader object by hand everytime you want to use it. For this task i created a small class generator that allows you to select the target database and tables you want to access. After the classes are generated, you query the table through an autogenerated access function. this does not handle joins yet. A more generic way to load data that contains any number of fields would be something like this: public class CMyClass { public Dictionary<string,string>Field = new Dictionary<string,string>(); public void LoadRecord(MySqlDataReader r){ DataTable schemaTable = r.GetSchemaTable(); foreach (DataRow row in schemaTable.Rows) { string column = row["ColumnName"].ToString(); string value = r[column].ToString(); if (value == "System.Byte[]") value = ByteToString((byte[])r[column]); Field.Add(column, value); } } }When I get a little more time, I will combine these two techniques so that if unexpected fields are encountered as from a join, the overflow unrecgonized fields will be added to a Dictionary so they can at least be accessed as string values. Not perfect but workable and easy. Update: Ok I was able to use a combination of both techniques. After some benchmarking, I found that the code below seems to be the quickest way to access unknown members. In the initilization function, you call GetSchemaTable once. If you encounter ambiguous column names, you auto rename subsequent ones columnName_1. public object GetRaw(string field){ if(Schema.ContainsKey(field)) return RawValues[Schema[field]]; return new object(); } public Ctblmsgs(IDataReader r, Dictionary<string, int> schema) { Schema = schema; RawValues = new object[r.FieldCount]; r.GetValues(RawValues); Comments: (2)On 02.20.18 - 8:19am Jerhill wrote:
On 08.13.18 - 8:45pm Robert wrote:
|
About Me More Blogs Main Site |
||