Problem
You have defined a business object and XAF has generated the necessary UI to enable you to carry out CRUD functionality; however, you now wish to be able to add a new instance of the business object programmatically.
Solution
In your chosen module, add a controller to the module. Drag a SimpleAction onto the Controller’s design surface. Give the SimpleAction a suitable name and a caption then handle the <SimpleActionName>_Execute event in order to add a new instance of your business object to the View’s ObjectSpace.
Discussion
Given the following definition of a business object named Book:-
using System;
using DevExpress.Xpo;
using DevExpress.ExpressApp;
using DevExpress.Persistent.Base;
using DevExpress.Persistent.BaseImpl;
using DevExpress.Persistent.Validation;
namespace ObjectSpaceExample.Module {
[DefaultClassOptions]
public class Book : BaseObject {
public Book(Session session) : base(session) { }
private string _Author;
public string Author {
get {
return _Author;
}
set {
SetPropertyValue("Author", ref _Author, value);
}
}
private string _Title;
public string Title {
get {
return _Title;
}
set {
SetPropertyValue("Title", ref _Title, value);
}
}
private string _Publisher;
public string Publisher {
get {
return _Publisher;
}
set {
SetPropertyValue("Publisher", ref _Publisher, value);
}
}
}
}
Assuming we now wish to add an instance of this business object programmatically, add a ViewController to the module and drag a SimpleAction onto the design surface. Handle the Execute event of the SimpleAction to add the new instance.
using System;
using System.ComponentModel;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
using DevExpress.ExpressApp;
using DevExpress.ExpressApp.Actions;
using DevExpress.Persistent.Base;
namespace ObjectSpaceExample.Module {
public partial class BookController : ViewController {
public BookController() {
InitializeComponent();
RegisterActions(components);
}
private void AddBookAction_Execute(object sender, SimpleActionExecuteEventArgs e) {
Book book = View.ObjectSpace.CreateObject<Book>();
book.Author = "Me";
book.Title = "A Book by Me";
book.Publisher = "Me";
View.ObjectSpace.CommitChanges();
View.ObjectSpace.Refresh();
}
}
}
Points to note: we use the View’s ObjectSpace to create the new instance of our business object, committing changes when we have done so to persist the object and then calling Refresh() on the ObjectSpace to refresh the View. You can read more about ObjectSpace in our documentation.