Joel Clark
Joel Clark

Reputation: 43

Table-per-Type Code First - How to differentiate if Base type is sub type

I'm certain that my issue extends from a misinterpretation of exactly how Base type/Sub type entities are related, but bear with me.

Say I have two classes:

public class Business
{
    public int UniqueID { get; set; }
    public string Name { get; set; }
}

public class BusinessType1 : Business
{
    public string SomeRelatedThing { get; set; }
}

public class BusinessType2 : Business
{
    public string SomeNotRelatedThing { get; set; }
}

In my application, I am using the base type for the most part. Some pages are contextual to the Sub types however, but need to be versatile enough to handle either (DNRY).

The page is only given the base type in context, and must load data from either BusinessType1 or BusinessType2.

The problem I am facing is that I need to ascertain if the base type (Business) is either linked with BusinessType1 or BusinessType2. I would prefer to do this without making a query to determine if the key exists in each table.

As far as I can see, this is not possible - hence my question;

Is there a way to achieve this using minimal queries to the DB?

Upvotes: 1

Views: 36

Answers (1)

Alexander Polyankin
Alexander Polyankin

Reputation: 1887

I'll try to extend @Hopeless with examples.

Fetch all entities and after that determine base type:

var entities = context.Business.ToList();
foreach(var baseEntity in entities)
{
    // some common logic for base entity type

    if (baseEntity is BusinessType1)
    {
        var concreteEntity = (BusinessType1)baseEntity;
        // some logic for entity of BusinessType1
    }
}

Fetch entities only with concrete type:

var concreteEntities = context.Business.OfType<BusinessType1>().ToList();
// some logic for entities of BusinessType1

As you can see, you don't need to perform any additional queries with Entity Framework.

Upvotes: 1

Related Questions