Is it possible to query EF by an interface and get the data castable in their concrete type ?
Let’s say I got:
public interface IBaseBlock
{
int Id { get; set; }
string Name { get; set; }
}
public class ContentBlock : IBaseBlock
{
public int Id { get; set; }
public string Name { get; set; }
public string Content { get; set; }
}
public class VideoBlock : IBaseBlock
{
public int Id { get; set; }
public string Name { get; set; }
string string VideoUrl { get; set; }
}
So, I want to be able to get a list from entity framework based on IBaseBlock and then cast them into their concret types to get the additional data.
Now, I know it’s possible to do it with nhibernate (http://stackoverflow.com/questions/3612816/nhibernate-query-all-objects-implementing-an-interface), and I know all it does is create a bunch of SQL queries, but all in one database round trip. I also don’t care much for additional data when the query is issued (I don’t want to be able to add wheres and order by, etc.) I just need to filter by the common fields (Id and Name).
Thanks
Entity framework doesn’t support querying by interface (EF doesn’t support interfaces at all). It supports only mapped entity inheritance. To make it work you must change your
IBaseBlockinterface toBaseBlockabstract class and map inheritance (probably TPC). Using inheritance has some other pitfalls. For example primary key of any entity must be unique in the whole inheritance tree.As a side note EF currently doesn’t support multiple queries within single roundtrip so when querying inheritance tree it creates one big query with unions.