Access properties of extending class in a base class query from DB with Entity Framework TPH pattern

StackOverflow https://stackoverflow.com/questions/23656279

سؤال

Probably the questin title is not self-explanationary.

I have an ASP.NET MVC5 project with Entity Framework 6. I use code first and I've implemented a TPH pattern for an entity.

There's a base Request entity (I've removed most fields, it's just an example).

public class Request
    {
        public int Id { get; set; }
        public string Title { get; set; }
    }

also there's some models with exclusive properties that extend it:

public class RequestQuestion : Request
    {
        public string Question { get; set; }
        public string Answer { get; set; }
    }

public class RequestForWork : Request
    {
        public string WorkName { get; set; }
    }

Each of them is added to the EntityContext:

public DbSet<Request> Requests { get; set; }
public DbSet<RequestQuestion> RequestQuestions { get; set; }
public DbSet<RequestForWork> RequestForWorks { get; set; }

When I create some of the requests I add them like this:

var db = new EntityContext();
var requestQuestion = new RequestQuestion{ some initialization };
this.db.Requests.Add(requestQuestion);
this.db.SaveChanges();

And here comes the question. When I query requests of the user

var requests = this.db.Students.Find(userId).Requests.ToList();

in debug I can access the properties of the extending class for every request through the base. So, is there a way to somehow get a type of class that is extending the selected entity and to access it's properties?

Currently to build a list of all requests and fill some viewmodel with data I need to seperately select every type of request and fill a global list from these seperate selects.

هل كانت مفيدة؟

المحلول

You need to cast the base type to its subtype and test for null

foreach (r in requests)
{
   var rq = r as RequestQuestion;
   if(rq != null)
   {
      string rq = rq.Question
   }

   var rfw = r as RequestForWork;
   if(rfw != null)
   {
      string wn = rfw.WorkName;
   }
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top