|
I have worked on CSLA on few projects and I am very much impressed from all of its features. However not every application wants to use CSLA but may be some features out of it. This post is about adding IsDirty and IsNew capabilities to our object. I used CSLA as reference for create these classes.
Base Classes Definitions
ObjectBase
public class ObjectBase
{
private bool _isDirty;
private bool _isNew = true;
public bool IsDirty
{
get { return _isDirty; }
}
public bool IsNew
{
get { return _isNew; }
}
protected void MarkDirty()
{
_isDirty = true;
}
protected void MarkClean()
{
_isDirty = false;
}
protected void MarkAsNew()
{
_isNew = true;
}
protected void MarkAsOld()
{
_isNew = false;
_isDirty = false;
}
}
ObjectListBase
public class ObjectListBase<T> : List<T> where T : ObjectBase
{
public bool IsDirty
{
get
{
foreach (T item in this)
{
if (item.IsDirty)
return true;
}
return false;
}
}
}
Using Base Classes
To use these base classes, simply inherit your business object from ObjectBase and collection objects from ObjectListBase. Let take example:
Suppose a class Employee represents an employee entity and its collection class EmployeeList.
Employee
public class Employee : ObjectBase
{
// Member Variables
private int _employeeCode;
private string _employeeName;
private decimal _salary;
// Public properties
public int EmployeeCode
{
get { return _employeeCode; }
set
{
if (_employeeCode != value)
{
_employeeCode = value;
base.MarkDirty();
}
}
}
public string EmployeeName
{
get { return _employeeName; }
set
{
if (_employeeName != value)
{
_employeeName = value;
base.MarkDirty();
}
}
}
public decimal Salary
{
get { return _salary; }
set
{
if (_salary != value)
{
_salary = value;
base.MarkDirty();
}
}
}
// Constructor
public Employee()
{
}
public void Fetch(int employeeCode)
{
// Code to fetch employee
base.MarkAsOld();
}
public void Save()
{
// Code to save employee
if (base.IsNew)
{
// Code Insert into database
}
else
{
// Code to Update into databse
}
base.MarkClean();
base.MarkAsOld();
}
}
EmployeeList
public class EmployeeList : ObjectListBase<Employee>
{
public static EmployeeList GetAllEmployees()
{
EmployeeList employes = new EmployeeList();
employes.FetchAll();
}
protected EmployeeList()
{
}
protected void FetchAll()
{
// Code to fetch employee list and
// add to this list
}
public void Save()
{
foreach (Employee employee in this)
{
if (employee.IsDirty)
{
employee.Save();
}
}
}
}
Using Objects
See the code below:
EmployeeList employess = EmployeeList.GetAllEmployees();
// ..
// do operation of list
// ..
// Saves the list
if (employess.IsDirty)
{
employess.Save();
}
Above code fetch list employee from database. You may perform add/edit operations on this. The class will manage the dirty and new state of object itself and Saves only those object in which changes are done. In this way we can save unnecessary trips to database.
|