/// <summary> /// Creates a row by fetching it from a result set. /// </summary> /// <param name="result">The result.</param> /// <returns></returns> internal static MySqlRow FetchFromResult(MySqlResult result) { // fetch data IntPtr valueArr = MySqlNative.mysql_fetch_row(result.Handle); if (valueArr == IntPtr.Zero) { return(null); } IntPtr lengthArr = MySqlNative.mysql_fetch_lengths(result.Handle); int numFields = (int)MySqlNative.mysql_num_fields(result.Handle); // create row MySqlRow row = new MySqlRow(); row.result = result; row.values = new object[numFields]; // lengths long[] length = new long[numFields]; Marshal.Copy(lengthArr, length, 0, numFields); // values IntPtr[] valuePtrs = new IntPtr[numFields]; Marshal.Copy(valueArr, valuePtrs, 0, numFields); for (int i = 0; i < numFields; i++) { row.values[i] = result.Fields[i].CastFrom(Marshal.PtrToStringAnsi(valuePtrs[i])); } return(row); }
/// <summary> /// Fetches the next row and casts it to a model. /// </summary> /// <typeparam name="T"></typeparam> /// <returns></returns> /// <exception cref="System.Exception"> /// The provided type must be a model /// or /// The provided model has no attribute /// or /// The provided model does not match the table /// or /// The model field ' + field.Name + ' has no attribute /// </exception> public T Fetch <T>() { // test if (!typeof(Model).IsAssignableFrom(typeof(T))) { throw new Exception("The provided type must be a model"); } // get type data Type t = typeof(T); // get model attributes ModelAttribute modelAtt = t.GetCustomAttribute <ModelAttribute>(); // check table if (modelAtt.Name.ToLower() != Fields[0].Table.ToLower()) { throw new Exception("The provided model does not match the table"); } // create object obj = null; // fetch MySqlRow row = Fetch(); if (row == null) { return(default(T)); } // get fields foreach (FieldInfo field in t.GetFields()) { // get field attributes ModelFieldAttribute fieldAtt = field.GetCustomAttribute <ModelFieldAttribute>(); // find mysql field for (int i = 0; i < Fields.Length; i++) { if (Fields[i].Name == fieldAtt.Name) { if (fieldAtt.Primary) { obj = Activator.CreateInstance(typeof(T), row.Values[i]); } else if (obj == null) { throw new Exception("The model does not define a valid primary key"); } field.SetValue(obj, row.Values[i]); } } } return((T)obj); }
/// <summary> /// Fetches the next row in the set. /// </summary> /// <returns></returns> public MySqlRow Fetch() { if (fields == null) { FetchFields(); } return(MySqlRow.FetchFromResult(this)); }