The problem is I have a base class where I don't have a strong name of the type yet. But, in the base class, I want to be able to retrieve the entity.
I have fixed the problem using reflection:
/// <summary>
/// Gets the currently loaded object represented by this page
/// </summary>
protected T CurrentObject
{
get
{
// Create or get object
object entity = null;
if (_pageMode == ObjectPageBase<T>.ObjectPageMode.Edit)
{
// Load existing, get constructor info
List<Type> constructorArgumentTypes = new List<Type>();
List<object> constructorArguments = new List<object>();
foreach (ObjectIdentifier identifier in _identifiers)
{
constructorArgumentTypes.Add(identifier.Type);
constructorArguments.Add(identifier.Value);
}
// Get constructor info
ConstructorInfo constructorInfo = typeof(T).GetConstructor(constructorArgumentTypes.ToArray());
// Check if there is a valid constructor
if (constructorInfo == null)
{
// Throw exception
throw new ObjectSaveException();
}
// Invoke constructor
entity = (T)constructorInfo.Invoke(constructorArguments.ToArray());
}
else
{
// Create new, get constructor info
ConstructorInfo constructorInfo = typeof(T).GetConstructor(new Type[] { });
if (constructorInfo == null)
{
// Throw exception
throw new ObjectSaveException();
}
// Invoke constructor
entity = (T)constructorInfo.Invoke(null);
}
// Return object
return (T)entity;
}
}
The ObjectIndentifier object is a simple class which contains the identifier, type of the identifier and the value if one. This way, I can runtime load / save objects without knowing the type. This saves me a LOT of time when I want to create an edit page for a specific object. I can now simple derive from the base class which handles the loading / saving of the object and I only need to worry about the object representation itself.
If there is a better way, please let me know!