简体   繁体   English

使用代码优先实体框架进行继承

[英]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. 我使用代码优先模式实现了继承(也就是说,我有一个基类Request和其他类将其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. 我无法找到一种简单的方法来执行此操作,因为我总是不得不将类型转换为Request,这意味着我失去了所有子类功能以及辨别我所拥有的类的能力。

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. 问题在于,到目前为止,我的所有请求都属于Request类型(我相信这是foreach的要求),因此我不知道它们的真正含义。

It's just little issues like this that I keep running into when using inheritance with code-first. 在通过代码优先使用继承时,我经常遇到这样的小问题。 Am I doing something wrong? 难道我做错了什么?

It seems that the framework/language doesn't provide much beyond this as far as functionality 就功能而言,似乎框架/语言并没有提供太多其他功能

No, because that's not EF's responsibility. 不,因为这不是EF的责任。 It does a fine job materializing the correct sub type for you and then it's job is over. 它为您实现了正确的子类型做得很好,然后工作结束了。 EF is about data. EF与数据有关。 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. 这正是使用“干” POCO进行继承时的方式。 Whenever you feel the need to do something like if (instance is MySubType) usually some design flaw becomes apparent. 每当您觉得需要执行某些操作if (instance is MySubType)通常会出现一些设计缺陷。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM