Friday, September 18, 2009

Persistent interfaces, part 2

In the previous post I described existing requirements to persistent interfaces. Now let’s talk about interface queries.

In most cases interface query is no more than a union of queries for every interface implementor, e.g., if we have the following Domain model,

public interface IAnimal : IEntity
{
  [Field]
  string Name { get; set; }
}

[HierarchyRoot]
public class Dog : Entity, IAnimal
{
  [Field, Key]
  public int Id { get; private set; }

  [Field]
  public string Name { get; set; }
}

[HierarchyRoot]
public class Cat : Entity, IAnimal
{
  [Field, Key]
  public int Id { get; private set; }

  [Field]
  public string Name { get; set; }
}

then Query<IAnimal>.All (query for all instances that implement IAnimal interface) will be translated into the following SQL code:

SELECT a.Id, a.TypeId, a.Name FROM Dog a 
UNION
SELECT b.Id, a.TypeId, b.Name FROM Cat b

As I mentioned earlier, to make this work we require that:

  • all corresponding fields in all implementors of an interface have equal SQL type;
  • all implementors of an interface have equal key structure;
  • all implementors of an interface have unique keys within interface implementors domain. Last one is achieved in most cases by sharing the same key generator instance for all hierarchies that have implementors of concrete interface.

DataObjects.Net 4 supports indexed views/materialized views for persistent interfaces. This could be achieved by marking interface type with MaterializedView attribute, e.g.:

[MaterializedView]
public interface IAnimal : IEntity
{
  …
}

In this case DataObjects.Net 4 will investigate the possibility of creating indexed view/materialized view in currently used Storage. If Storage supports the feature then corresponding indexed view will be created; otherwise, a regular table will be created and its contents will be updated by DataObjects.Net 4 itself during persist routine.

P.S. Indexed view support is in development stage for now as well as persistent interfaces support.

CodeProject

No comments:

Post a Comment