How to use interface properties with CodeFirst

An imperfect solution is to just merge these interfaces you want to persist into base classes and break down the underlying objects with subclasses. EF does support this, and if you go with Table Per Hierarchy (the default), you can sort all of the underlying subclassed objects by a shared property using a regular LINQ query from EF instead of having to get crafty and do things like write raw SQL or get multiple lists into memory and sort the union without the help of the DB, like you would with Cel’s solution of interfaces and adapters.

You could also take the child/parent types of interfaces as generics, so that when the implementer uses concrete classes in the Db they can mostly use your interfaces, but tell EF to use concrete classes:

public interface IParent<out TChild>
    where TChild : IChild
    ICollection<TChild> Children { get; set; }

Someone could create their Db classes like:

public class Parent : IParent<Child>
. . .

But still use them like:

IParent<IChild> parents = db.Parents.Include(p => p.Children).ToArray();

Because the generic is marked out, the generic is covariant and therefore can take anything that meets the generic’s restrictions, including the above cast up the type tree to the IChild interface.

That said, if you really want to persist interfaces, the right answer is probably to use NHibernate:
How to map an interface in nhibernate?

And some coders recommend you keep interfaces on entities in any ORM limited to a few shared properties, or risk misuse:
Programming to interfaces while mapping with Fluent NHibernate

Leave a Comment