Problem
You wish to use XPO as an ORM tool. You have an existing hierarchy of business objects and you do not wish to implement any extra interfaces.
Solution
Assume you have the following hierarchy of business objects where Employee inherits from Person:-
//GS - Create an existing hierarchy
public class Person {
private string _Name;
public string Name {
get { return _Name; }
set {
_Name = value;
}
}
private DateTime _DateOfBirth;
public DateTime DateOfBirth {
get { return _DateOfBirth; }
set {
_DateOfBirth = value;
}
}
public Person() {
}
}
public class Employee : Person {
private string _EmployeeNumber;
public string EmployeeNumber {
get { return _EmployeeNumber; }
set {
_EmployeeNumber = value;
}
}
public Employee() {
}
}
After adding support for XPO the hierarchy will look like this:-
[Persistent]
public class Person {
private int _Id;
[Key(true)]
public int Id {
get { return _Id; }
set {
_Id = value;
}
}
private string _Name;
public string Name {
get { return _Name; }
set {
_Name = value;
}
}
private DateTime _DateOfBirth;
public DateTime DateOfBirth {
get { return _DateOfBirth; }
set {
_DateOfBirth = value;
}
}
public Person() {
}
}
[Persistent]
public class Employee : Person {
private string _EmployeeNumber;
public string EmployeeNumber {
get { return _EmployeeNumber; }
set {
_EmployeeNumber = value;
}
}
public Employee() {
}
}
Creating, modifying and saving objects from this hierarchy are now done in the same way as if the objects inherited from one of the XPO classes in the first place. The full example now looks like this:-
using System;
using DevExpress.Xpo;
class Program {
static void Main(string[] args) {
XpoDefault.Session.Save(new Employee() {
Name="Gary",
DateOfBirth = DateTime.Parse("24/01/1970"),
EmployeeNumber = "RA 1234"
});
}
}
[Persistent]
public class Person {
private int _Id;
[Key(true)]
public int Id {
get { return _Id; }
set {
_Id = value;
}
}
private string _Name;
public string Name {
get { return _Name; }
set {
_Name = value;
}
}
private DateTime _DateOfBirth;
public DateTime DateOfBirth {
get { return _DateOfBirth; }
set {
_DateOfBirth = value;
}
}
public Person() {
}
}
[Persistent]
public class Employee : Person {
private string _EmployeeNumber;
public string EmployeeNumber {
get { return _EmployeeNumber; }
set {
_EmployeeNumber = value;
}
}
public Employee() {
}
}
Discussion
To enable the initial object hierarchy to be persisted by XPO the following steps were carried out:-
- The Persistent attribute was added to both the Person and the Employee Classes.
- A new property (Id) was added to Person (this is inherited by Employee).
- The Key attribute was added to the Id property and a boolean parameter of true was passed to it to indicate that the key should be generated automatically.
Technorati tags:
XPO Cookbook