We help IT Professionals succeed at work.

Separating columnName and Value in C#

rowmark
rowmark asked
on
hi, I have a employee object as shown below
class emp
    {
        public int EmpID { get; set; }
        public string EmpName { get; set; }
        public int deptID { get; set; }

    }

Open in new window


I need to create a mapping either in this class or a different class to map the properties with column name of my SQL
for eg. EmpdID="employeeID"
        EmpName="EmployeeName"
        deptID="DepartmentID"

Open in new window

for eg: emp e=new emp();
        e.EmpID=1;
        e.EmpName="tommy";    
        e.deptID=10;
When the emp object is populated and passed to the buildValues function it should return array of ComumnName(e.g.employeeID):Value(e.g.1),EmployeeName:tommy,DepartmentID:10)



string[] values=buildValues(emp);


public string[] buildValues(emp e)
{
  string[] values=null;


  return values;
}

Open in new window

I have 2 questions: 1. Where do I specify the mappings 2. How do I use the mappings in my buildValues function shown above and build the values string array.

I would really appreciate if you can help me with this
Comment
Watch Question

Commented:
If you want automated tool/generated code then you can use visual studio's built-in facilities. I haven't used this method in a while so the steps given below might not be accurate.

1. Add DB connection in Server Explorer window
2. Add new data source to your project & specify the DB connection
3. Add new data set (.xsd file) and drag & drop the tables you are interested in

This won't provide the exact things you are looking for but I think you are probably trying to build framework for the mapping and there is a pre-existing tool so why not use it?

=============

If you want to do it yourself, I would suggest using Attributes (http://msdn.microsoft.com/en-us/library/z0w1kczw.aspx) and Reflection (http://msdn.microsoft.com/en-us/library/ms173183.aspx). See the sample.

[System.AttributeUsage(System.AttributeTargets.Property)]
public class SqlColumnName : System.Attribute
{
    private string name;
    public SqlColumnName(string name)
    {
        this.name = name;
    }
}

class emp
    {
        [SqlColumnName("employeeID")]
        public int EmpID { get; set; }
        public string EmpName { get; set; }
        public int deptID { get; set; }

    }

Dictionary<string, string> buildValues(emp e)
{
    Dictionary<string, string> rv = new Dictionary<string, string>();

    foreach (PropertyInfo pi in e.GetType().GetProperties())
    {
        object[] attribs = pi.GetCustomAttributes(false);
        foreach (object o in attribs)
        {
            SqlColumnName sqlName = o as SqlColumnName;
            if (sqlName != null)
            {
                rv[sqlName.name] = pi.GetValue(e, null).ToString();
                break;
            }
        }
    }

    return rv;
}

Open in new window