Skip to content

Instantly share code, notes, and snippets.

@julesx
Last active November 15, 2016 18:46
Show Gist options
  • Save julesx/98a674efff02ad05cb3df8bc8854c202 to your computer and use it in GitHub Desktop.
Save julesx/98a674efff02ad05cb3df8bc8854c202 to your computer and use it in GitHub Desktop.
private TSqlRecord MapToClass<TSqlRecord>(SqlDataReader reader) where TSqlRecord : class, ISqlRecord
{
var returnedObject = Activator.CreateInstance<TSqlRecord>();
try
{
var modelProperties = returnedObject.GetType().GetProperties();
var schemeTable = reader.GetSchemaTable();
foreach (var t in modelProperties)
{
var attributes = (MappingAttribute[])Attribute.GetCustomAttributes(t, typeof (MappingAttribute), true);
if (attributes.Length > 0 && attributes[0].ColumnName != null)
{
dynamic value = null;
if (!schemeTable.Rows.Cast<DataRow>().Any(row => row["ColumnName"].ToString() == attributes[0].ColumnName))
continue;
if (reader[attributes[0].ColumnName] != DBNull.Value)
{
var tType = t.PropertyType;
if (t.PropertyType.IsGenericType && t.PropertyType.GetGenericTypeDefinition() == typeof (Nullable<>))
{
tType = Nullable.GetUnderlyingType(t.PropertyType);
}
value = Convert.ChangeType(reader[attributes[0].ColumnName], tType);
}
t.SetValue(returnedObject, value, null);
}
}
}
catch (Exception ex)
{
_nLogger.Error(ex);
}
return returnedObject;
}
public class SqlUser : SqlBase
{
[Mapping(ColumnName = "Id")]
public virtual long Id { get; set; }
[Mapping(ColumnName = "FirstName")]
public virtual string FirstName { get; set; }
[Mapping(ColumnName = "LastName")]
public virtual string LastName { get; set; }
[Mapping(ColumnName = "UserName")]
public virtual string UserName { get; set; }
[Mapping(ColumnName = "Activated")]
public virtual bool Activated { get; set; }
[Mapping(ColumnName = "Salt")]
public virtual string Salt { get; set; }
[Mapping(ColumnName = "Password")]
public virtual string Password { get; set; }
[Mapping(ColumnName = "AccountId")]
public virtual long AccountId { get; set; }
[Mapping(ColumnName = "UserTypeId")]
public virtual int UserTypeId { get; set; }
[Mapping(ColumnName = "GroupId")]
public virtual long GroupId { get; set; }
[Mapping(ColumnName = "SelectedDatabaseId")]
public virtual long SelectedDatabaseId { get; set; }
[Mapping(ColumnName = "Deleted")]
public virtual DateTime? Deleted { get; set; }
[Mapping(ColumnName = "DeletedById")]
public virtual long? DeletedById { get; set; }
[Mapping(ColumnName = "ResetToken")]
public virtual string ResetToken { get; set; }
public string Name => (FirstName + " " + LastName).Trim();
public string DeletedBy => DeletedById != null && DeletedById > 0 ? new UsersModel().GetById((long)DeletedById).Name : "";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment