Inheritance of the structure of objects - returns only the parent type

I Supplier class:

public class Supplier {
    ....
    ....
    ....
}

I also have a Subcontractor class, and Subcontractor is a provider:

public class Subcontractor:Supplier {
    ....
    ....
    ....
}

In my db, I have a provider table with data and another table with an id field that acts as a foreign key for the provider table, and I also have subcontent data.

In the framework entity file edmx, I declared the inheritance relation: inheritance

Now I want to get all suppliers that are not subcontractors, so I do:

context.Suppliers.OfType<Supplier>();

But it also returns subcontractors ..

How can I get only Suppliers who are not subcontractors?

+3
source share
3 answers

Try:

context.Suppliers.Where(s => !(s is Subcontractor));

Edit

, Supplier, LINQ to Entities :

context.Suppliers.Where(s => !(s is Subcontractor) 
                          && !(s is DerivedClass2)
                          && !(s is DerivedClass3)); // etc.

Entity SQL , . LINQ.

- OfTypeOnly<TEntity>, .

+3

LINQ, , .

public static class MyLinqExtensions
{
    public static IQueryable<T> OfTypeOnly<T>(this IQueryable<T> query)
    {
        Type type = typeof (T);
        IEnumerable<Type> derivedTypes = Assembly
            .GetAssembly(type)
            .GetTypes()
            .Where(t => t.IsSubclassOf(type));

        return query.ExceptTypes(derivedTypes.ToArray());
    }

    public static IQueryable<T> ExceptTypes<T>(this IQueryable<T> query, params Type[] excludedTypes)
    {
        if (excludedTypes == null)
            return query;

        return excludedTypes.Aggregate(query,
            (current, excludedType) => current.Where(entity => entity.GetType() != excludedType));
    }
}

:

// Get only entities of type Supplier, excluding subclasses.
var suppliers = context.Suppliers.OfTypeOnly<Supplier>();
+1
context.Suppliers.Where(s => s.GetType() == typeof(Supplier));
-1
source

All Articles