Kye
Kye

Reputation: 4495

Inheritance with code-first Entity Framework

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?

Upvotes: 0

Views: 123

Answers (1)

Gert Arnold
Gert Arnold

Reputation: 109080

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.

Upvotes: 1

Related Questions