jeudi 17 décembre 2015

Implementing validation rules inside of class

I have class like this

public class EmployeeInfo
{
    public string EmployeeName { get; set; }
    public string PhoneNumber { get; set; }
    public string Office { get; set; }
    public string Department { get; set; }
}

I've created method that takes SPListItemCollection as parameter and returns list of object of EmployeeInfo class.There is no restrictions inside SPList and when you create new item you can leave some of the fields empty, so I've used reflection to determine if field is null and then insert empty string when populating EmployeeInfoobject to avoid exceptions.

 public List<Models.EmployeeInfo> GetEmployeeInfo(SPListItemCollection splic)
 {

        var listEmployeeInfo = new List<Models.EmployeeInfo>();
        var propertyNames = new List<string>() { "EmployeeName", 
                                                 "Department", 
                                                 "Office", 
                                                 "PhoneNumber};

        foreach (SPListItem item in splic)
        {
            var employeeInfo = new Models.EmployeeInfo();


            foreach (var propertyName in propertyNames)
            {
                string newData = "";
                if (item[propertyName] != null)
                {
                    newData = item[propertyName].ToString();
                }

                employeeInfo.GetType().GetProperty(propertyName).SetValue(employeeInfo, newData, null);


            }
            listEmployeeInfo.Add(employeeInfo);
        }

        return listEmployeeInfo;

    }

Later I've learned that it is bad practice to use reflection inside of nested loops , so I'm looking for different approach. Is there any chance I can make some pre Validation Rules inside EmpployeeInfo class , something like Validation method or to write some code inside class properties and than inside of GetEmployeeInfo method just to populate properties by calling that method? Thank you.





Aucun commentaire:

Enregistrer un commentaire