I have a simple
ActiveRecord class:
[ActiveRecord]
public class Employee
{
[PrimaryKey(PrimaryKeyType.GuidComb)]
public Guid? Id { get; set; }
[Property]
public string FirstName { get; set; }
[Property]
public string LastName { get; set; }
}
I then create a create/edit form on my UI. To update the database is easy with the
ASP.NET MVC Framework and
ActiveRecord:
In my controller:
public void Update(Guid? Id)
{
var emp = DomainFactory.Get<Employee>(Id);
BindingHelperExtensions.UpdateFrom(emp, Request.Form);
emp.Save();
//Render View
}
Ok now I want to add a
Department Object to the
Employee:
[BelongsTo(Cascade = CascadeEnum.SaveUpdate)]
public Department Department { get; set; }
On my form page I create a select dropdown with a list of Departments. The value of the select options is the
Guid Id of the
Department.
MVC does not know anything about
ActiveRecord so it cannot convert the
Guid (actually it is of type
string in the Forms Collection) to type of
Department.
In order to continue using the
UpdateFrom Binder method we need to create a
TypeConverter for the
ActiveRecord Objects:
1 public class ARConverter<T> : TypeConverter
2 {
3 public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
4 {
5 if (sourceType == typeof(string))
6 {
7 return true;
8 }
9
10 return base.CanConvertFrom(context, sourceType);
11 }
12
13 public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value)
14 {
15
16 if (value.GetType() == typeof(string))
17 {
18 return ActiveRecordMediator.FindByPrimaryKey(typeof(T), new Guid((string) value));
19 }
20 return base.ConvertFrom(context, culture, value);
21 }
22 }
All I need to do is decorate my
ActiveRecord classes with this
TypeConverter:
[ActiveRecord]
[TypeConverter(typeof(ARConverter<Department>))]
public class Department
Now when
MVC updates from the Forms Collection it will convert the Id to the actually object from the database.