Article information
Article relates to
Telerik OpenAccess ORM
Created by
Zoran Kostov
Last modified
April 26, 2010
Last modified by
Serge Ovanesyan
The context is quite easy to handle in a desktop application. One of the most elegant and generic ways to do so is managing one scope per thread by storing it in a thread-specific LocalDataStoreSlot. Here is a sample ContextFactory class that contains one static method for scope-retrieval:
public
class
ContextFactory
{
static
NorthwindEntityDiagrams ObtainContext()
NorthwindEntityDiagrams context =
null
;
string
key = Thread.CurrentContext.ContextID.ToString();
LocalDataStoreSlot slot = Thread.GetNamedDataSlot(key);
if
(slot !=
)
context = (NorthwindEntityDiagrams) Thread.GetData(slot);
}
(context ==
context =
new
NorthwindEntityDiagrams();
(slot ==
slot = Thread.AllocateNamedDataSlot(key);
Thread.SetData(slot, context);
return
context;
By obtaining the context using this approach all the various forms and user controls in a desktop application can communicate using the same context instance given they are created on the same thread. That may seem suspicious for a multi-threaded scenario but it actually is not a very common case that controls created on different threads share the same business object. Sample scenario: We have a windows form with two user controls on it. The user controls are quite simple ones: the first contains one RadComboBox on it and the other a RadGridView. In the code-behind of both user-controls they have sample data-binding logic:
partial
ComboBoxUserControl : UserControl
...
private
void
ComboBoxUserControl_Load(
object
sender, EventArgs e)
var context = ContextFactory.ObtainContext();
IList<Customer> results = context.Customers.ToList();
this
.radComboBox1.DataSource = results;
.radComboBox1.DisplayMember =
"ContactName"
.radComboBox1.ValueMember =
"CustomerID"
GridUserControl : UserControl
GridUserControl_Load(
NorthwindEntityDiagrams ctx = ContextFactory.ObtainContext();
IList<Order> results = ctx.Orders.ToList();
radGridView1.DataSource = results;
The main form where both user controls are dropped has some own business logic. So it reuses the same Context instance.
Form1 : Form
Form1()
InitializeComponent();
.comboBoxUserControl1.Combo.SelectedIndexChanged +=
EventHandler(Combo_SelectedIndexChanged);
Combo_SelectedIndexChanged(
RadComboBox combo = ((RadComboBox)sender);
(combo.SelectedValue !=
customerId = combo.SelectedValue.ToString();
NorthwindEntityDiagrams context = ContextFactory.ObtainContext();
IList<Order> results = context.Orders.Where(x => x.CustomerID == customerId).ToList();
.gridUserControl1.Grid.DataSource = results;
Resources Buy Try