Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Using Attributes & Reflection to create a table map of a class (Class name: table name + Property identifier : column name), for when you don't want to use something better like an ORM / Entity Framework, I guess?
- // Example output at bottom
- // Attribute to import into your classes you want to make a tablemap for
- // for example: using DomainLayer.Attributes;
- public sealed class TableMapAttribute : Attribute
- {
- public string ColumnName { get; set; }
- public string TableName { get; set; }
- public TableMapAttribute(string? Name)
- {
- if(Name != null) ColumnName = Name;
- }
- public TableMapAttribute(string? tableName, bool isTableName=true)
- {
- if (tableName != null) TableName = tableName;
- }
- }
- // On the class level, define the table name
- // For each property you want to include, define the column name
- namespace BusinessLaag
- {
- [TableMap(tableName:"bestuurder")]
- public class Bestuurder
- {
- [TableMap(Name:"id")] // this is the column identifier
- public int? Id { get; set; }
- }
- }
- // Implement where deemed purposeful, pass any object into the function and it will give you the mappings (if you added any)
- // Example output:
- // {ClassName : Bestuurder, Bestuurder : bestuurder, Id : id, Naam : naam, Voornaam : voornaam, Adres : adres}
- public Dictionary<string, string> GetTableMapping(object myClass)
- {
- Dictionary<string, string> _mapping = new Dictionary<string, string>();
- string ClassName = myClass.GetType().Name;
- object[] classAttrs = myClass.GetType().GetCustomAttributes(true);
- foreach(object attr in classAttrs)
- {
- TableMapAttribute classAttr = attr as TableMapAttribute;
- try { _mapping.Add(ClassName, classAttr.TableName); } catch (Exception e) { };
- }
- PropertyInfo[] props = myClass.GetType().GetProperties();
- foreach (PropertyInfo prop in props)
- {
- object[] attrs = prop.GetCustomAttributes(true);
- foreach (object attr in attrs)
- {
- TableMapAttribute colAttr = attr as TableMapAttribute;
- if (colAttr != null)
- {
- if (colAttr.ColumnName != null)
- {
- string propName = prop.Name;
- string auth = colAttr.ColumnName;
- _mapping.Add(propName, auth);
- }
- }
- }
- }
- foreach (KeyValuePair<string, string> entry in _mapping)
- {
- if (entry.Key == ClassName) { _mapping.Add("ClassName", ClassName); break; }
- }
- return _mapping;
- }
Add Comment
Please, Sign In to add comment