ChBaeumer wrote:
Hi,
in my project I have serveral root entites and I like to define a static create method to instantiate the appropiate sub-entities using the discriminator value.
So far I have following:
<[ If IsSuperType ]>
public static <[ RootEntityName ]>DTO Create( Guid elementTypeId )
<[ Foreach Entity CrLf ]>
<[ If Not StringValueEquals DiscriminatorValue "" ]>
if ( elementTypeId.Equals( <[ DiscriminatorValue ]> ) )
{
return new <[ CurrentEntityName ]>DTO();
}<[ EndIf ]>
<[ NextForeach ]>
}<[ EndIf ]>
Following problems:
-
How do I get the .Net type of the Discriminator-Column?
This is necessary for the parameter declaration of the method.
- How do I get all Subtypes of an root entity?
- DiscriminatorValue seems not to be evaluated for StringValueEquals so it is not possible to check if an Value exists for the solution above
v2.6 TDL doesn't have the proper statements to do this, e.g. it doesn't have a foreach for all subtypes. You can easily create this in .lpt btw. You can include a .lpt template inside a TDL template so you can use the lpt template as an include in the TDL based entity templates without problem.
When using a .lpt include template, you've to work with the _activeObject member variable, which is a Hashtable, (see 'Grammar' section in SDK docs in lpt templates engine section), and the key "CurrentEntity" contains the current entity definition.
Your code then becomes:
<%
EntityDefinition entity = (EntityDefinition)((Hashtable)_activeObject)["CurrentEntity"];
if((entity!=null) && entity.IsHierarchyRoot && (entity.HierarchyType==InheritanceHierarchyType.TargetPerEntityHierarchy))
{
%>public static <%=entity.Name%>DTO Create(<%=entity.DiscriminatorField.DotNetType.ToString()%> elementTypeId)
{
<%
foreach(EntityDefinition subType in entity.GetSubTypes(false))
{
%> if( elementTypeId.Equals( <%=subType.DiscriminatorValue%> ))
{
return new <%=subType.Name%>DTO();
}
<% }
%>}
Haven't tested it but I think it should work properly. Pay special attention to subType.DiscriminatorValue, which is dumped into the output as-is. If your typeid is a Guid, you might want to compare the values in string form, or at least you need some support code to get working output.
For v3, this code has to be adjusted, however it won't be hard to migrate it (e.g. you ask the project for subtypes instead of the entity, you would also use the helper classes we're currently adding for .lpt templates for discriminator value output rather than this code above. )