0

Just having a few issues with inheritance in code-first entity framework.

I implemented inheritance using the code-first pattern (that is, I have a base class Request and other classes subclass it NewSpaceRequest.etc.

It seems that the framework/language doesn't provide much beyond this as far as functionality.

For instance, I wanted to have a view that had a list of all of the requests, with different text depending on the type of request. I couldn't work out an easy way to do that because I always had to typecast to Request, which means I lose all my subclass functionality and my ability to tell what class I had.

Anyway, I found a hacky way around this, and I have a list of requests in a view. I want to allow the user to click a link (one for each Request in the list) and be sent to an action that'll change depending on the type of request. The problem is that by this point all my requests are of type Request (I believe this is a requirement of foreach) so I have no idea what they really are.

It's just little issues like this that I keep running into when using inheritance with code-first. Am I doing something wrong?

3
  • Why would you ever need to upcast to Request? Commented Apr 10, 2014 at 6:28
  • Just to be clear: Your Request is not an HttpRequest but a class you defined yourself, is it? Commented Apr 10, 2014 at 7:29
  • @haim770: in my case, to use foreach properly. Casting to var is more useless. Commented Apr 10, 2014 at 8:36

1 Answer 1

1

It seems that the framework/language doesn't provide much beyond this as far as functionality

No, because that's not EF's responsibility. It does a fine job materializing the correct sub type for you and then it's job is over. EF is about data. Behavior is on the programmer's plate.

In your code you can use the whole arsenal of inheritance and polymorphism to get the behavior you want. The base class could have a method that the subclasses override to perform the required action. So you should direct the link-click to this method in the base class.

I lose (...) my ability to tell what class I had

So if you exploit this mechanism of polymorphism it's not necessary to know the specific type you're dealing with. That's exactly the way it is when doing inheritance with "dry" POCO. Whenever you feel the need to do something like if (instance is MySubType) usually some design flaw becomes apparent.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.