Search code examples
c#entityoftype

Entity Framework OfType() dynamically


How can you do:

Type ty = Type.GetType("Student");
var students = db.People.OfType(ty);

in a way that will work?

Why?

I only used people/students as an example, Here's a slightly more detailed explanation of why I might want to do this.

I wish to be able be able to store postal address information in a relational structure that pertains to a particular culture. My idea was to have a base type : "Address" and inherited types of it, eg: "UK_Address". Then my "People" entities would just have an "Address" reference. I would store the name of the specific address type as a string within the Person type, and use this name to dictate the behaviour of the program when interacting with addresses.

If that makes sense!? :s


Solution

  • If your looking for an answer along the lines of:

    Type ty = ...
    var students = db.People.OfType<ty>(); //Doesn't work, see below
    

    Then I don't think it will work without reflection. See

    IQueryable OfType<T> where T is a runtime Type