.net 使用实体框架实体作为业务对象?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/217655/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using Entity Framework entities as business objects?
提问by Aleksandar
I'm using Entity Framework O/R mapper from Microsoft and using entity classes (generated classes that are mapped to DB objects) as a business objects. Is this OK? Please state your cons or pros. What to do in a case of WCF communication between business layer and presentation, how to send those objects as data members?
我正在使用 Microsoft 的实体框架 O/R 映射器,并使用实体类(映射到 DB 对象的生成类)作为业务对象。这个可以吗?请说明你的缺点或优点。在业务层和表示之间进行 WCF 通信的情况下该怎么办,如何将这些对象作为数据成员发送?
采纳答案by YeahStu
I am using EF in this fashion and one nice feature is that generated entities are partial classes, allowing them to be extended in a way that is fairly protected from regeneration issues.
我正在以这种方式使用 EF,一个不错的特性是生成的实体是部分类,允许它们以一种可以避免重新生成问题的方式进行扩展。
Also take a look at this link on MSDNwhich describes some common usage scenarios with EF in regards to Business Logic.
回答by J.C.
First off, with 11k question views at the time of this writing, I'm a little surprised by the lack of answers and with all due respect, the quality of the answers, given a fairly straightforward question.
首先,在撰写本文时有 11,000 次问题查看,我对缺乏答案感到有些惊讶,但恕我直言,回答的质量非常简单,因为这是一个相当简单的问题。
So, now that I've vented a little bit, I'd like to address this question(s) because I think that it applies even more so today with the recent release of Entity Framework Code-First.
所以,既然我已经发泄了一点,我想解决这个问题,因为我认为它在今天更适用于最近发布的 Entity Framework Code-First。
"Using Entity Framework entities as business objects?"
“使用实体框架实体作为业务对象?”
A couple points of clarification before I began:
在我开始之前澄清几点:
When you say "business objects", I'm under the impression that these objects you refer to contain rules or logic ranging from, for example, simple validation (I.e required fields) to more complex logic (I.e. processing tax on a checkout).
I do not think that I can answer your follow up question regarding WCF. The reason for this is simply because I'm going to objectively answer your questions about EF as business objects which would then subjectively force me to take a stance proving contradictory of my attempt to genuinely and objectively answer said first question.
当您说“业务对象”时,我的印象是您所指的这些对象包含规则或逻辑,例如,从简单的验证(即必填字段)到更复杂的逻辑(即在结账时处理税款)。
我认为我无法回答您关于 WCF 的后续问题。这样做的原因很简单,因为我将客观地回答您关于 EF 作为业务对象的问题,这会主观地迫使我采取与我试图真正客观地回答上述第一个问题相矛盾的立场。
That said, onto your EF as business objects questions...
也就是说,将您的 EF 作为业务对象问题...
"I'm using Entity Framework O/R mapper from Microsoft and using entity classes (generated classes that are mapped to DB objects) as a business objects. Is this OK?"
“我正在使用 Microsoft 的实体框架 O/R 映射器,并使用实体类(映射到 DB 对象的生成类)作为业务对象。这样可以吗?”
Sorry, there simply is no right or wrong answer here. It depends on what your objective is and what you conclude to be the most reasonable design while fully understanding the advantages and disadvantages of doing so.
抱歉,这里没有正确或错误的答案。这取决于您的目标是什么,以及您在充分了解这样做的优点和缺点的同时得出的最合理设计的结论。
“Please state your cons or pros”
“请说明你的缺点或优点”
I'm glad you asked! I'll be happy to answer and my hope here is that given the pros and cons you are able to make an informed decision as to whether or not you believe using EF for your business objects is “OK”. Typically, I'd break out the pros and cons making it easy to “digest”, however, I don't think that is appropriate here because I think we'd be doing an injustice to such a very interesting topic which is also near and dear to my heart.
我很高兴你问了!我很乐意回答,我的希望是,鉴于利弊,您能够就您是否认为将 EF 用于您的业务对象“可以”做出明智的决定。通常,我会列出优点和缺点以便于“消化”,但是,我认为这不合适这里,因为我认为我们会对这样一个非常有趣的话题不公平,而且这个话题也很接近和亲爱的我的心。
First off, let me talk technically for a moment… You are able to use EF objects as your business objects there is nothing technically preventing you from doing so. As a matter of fact, EF Code-First (CF) makes this incredibly easy by allowing you to create POCOs and giving you the ability to apply data annotations for simple validation as well as implementing IValidatableObject for more complex validation. Pretty cool, eh?
首先,让我从技术上谈一谈……您可以使用 EF 对象作为您的业务对象,从技术上讲,没有什么可以阻止您这样做。事实上,EF Code-First (CF) 通过允许您创建 POCO 并让您能够应用数据注释以进行简单验证以及实现 IValidatableObject 以进行更复杂的验证,从而使这变得非常容易。很酷吧?
Therein lies the heart of the discussion.
这就是讨论的核心。
EF, or any ORM, is designed to support data management. Its main responsibility is data and therefore the objects you create are data centric. So, if you are attempting to also design your objects by behavior then you have a little bit of a conundrum on hand. In a nutshell this conundrum is called impedance mismatch. Picture this; you have two required use cases in your application:
EF 或任何 ORM 旨在支持数据管理。它的主要职责是数据,因此您创建的对象是以数据为中心的。所以,如果你还试图通过行为来设计你的对象,那么你手头就有一个难题。简而言之,这个难题称为阻抗失配。想象一下;您的应用程序中有两个必需的用例:
- A screen to edit a user
- A control to display a read-only subset of user information
- 编辑用户的屏幕
- 显示用户信息的只读子集的控件
If using EF (any flavor), or any ORM for that matter, you might gravitate towards using the same “User” object to handle the ability to save a user as well as fetching a user to pull the subset of read-only fields. You probably do so for one of a few reasons:
如果使用 EF(任何风格)或与此相关的任何 ORM,您可能倾向于使用相同的“用户”对象来处理保存用户以及获取用户以提取只读字段子集的能力。您这样做可能是出于以下几个原因之一:
- Like many developers, we have this seed planted in our brains during education “consolidating code” is of utmost importance or perhaps better known as DRY – Don't Repeat Yourself, and therefore you may look at duplication of code, such as properties, in a negative context.
- ORMs, such as EF 4.1, have technical limitations (and hackish work-arounds) such as mapping multiple POCOs/objects to the same database table thereby forcing you to regardless of your beliefs.
- It is a quick and easy way to get an application up and running
- It “feels” like the right thing to do
- 像许多开发人员一样,我们在教育过程中在大脑中种下了这颗种子“巩固代码”是最重要的,或者更广为人知的是 DRY – 不要重复自己,因此您可能会查看重复的代码,例如属性,一个消极的背景。
- ORM,例如 EF 4.1,有技术限制(和骇人听闻的变通方法),例如将多个 POCO/对象映射到同一个数据库表,从而迫使您不顾自己的信念。
- 这是启动和运行应用程序的一种快速简便的方法
- 它“感觉”是正确的做法
There are advantages and disadvantages of doing so and you could look at this is either a positive or negative way depending on your opinion.
这样做有好处也有坏处,你可以根据你的意见来看待这是一种积极或消极的方式。
I suppose if you believe in the normalization of code over behavior than you have succeeded greatly. You were able to limit the amount of code, potentially saving time, by writing a single object to handle your data and business use cases for that entity.
我想如果你相信代码规范化而不是行为,那么你已经取得了巨大的成功。您可以通过编写单个对象来处理该实体的数据和业务用例,从而限制代码量,从而可能节省时间。
And I suppose if you believe in the normalization of behavior over code than you have failed miserably. By saving on code you have sacrificed designing objects by their responsibilities potentially making it difficult to manage and subsequently increasing the cost to maintain.
而且我想,如果你相信行为规范化而不是代码,那么你就惨败了。通过节省代码,您已经牺牲了设计对象的职责,这可能使管理变得困难并随后增加维护成本。
Regardless of your opinion we can probably all agree that this business object has taken on multiple responsibilities and the behavior (not data!) of the object is secondary at best. Its main responsibility is the management of data and its secondary responsibilities are the processing the business rules, both simple & complex, involved with editing a user and displaying read-only user information. In object-oriented design (OOD), if the design of an object is characterized by its identity and behavior, than this object might be one confused individual as it doesn't adhere to the very definition of OOD.
不管您的意见如何,我们可能都同意这个业务对象承担了多项责任,并且对象的行为(不是数据!)充其量是次要的。它的主要职责是管理数据,其次要职责是处理简单和复杂的业务规则,涉及编辑用户和显示只读用户信息。在面向对象设计 (OOD) 中,如果对象的设计以其身份和行为为特征,那么该对象可能是一个令人困惑的个体,因为它不符合 OOD 的定义。
Something to consider from a technical standpoint, any time you request the user object you inherit a significant amount of overhead. This might include things such as all the properties and business rules when only displaying a subset of read-only information.
从技术角度考虑,任何时候请求用户对象都会继承大量开销。当仅显示只读信息的子集时,这可能包括诸如所有属性和业务规则之类的内容。
So what does all of this have to do with whether or not I should use EF to represent my business objects?
那么所有这些与我是否应该使用 EF 来表示我的业务对象有什么关系呢?
Well… While it is technically possible, there are differing philosophies (some good, some bad) on whether or not you should use EF, or any ORM, to represent your business objects. I gave a synopsis aimed at the heart of these philosophies above, but they are documented in much more detail by individuals such as Rocky Lhotka and Martin Fowler.
嗯……虽然在技术上是可行的,但对于是否应该使用 EF 或任何 ORM 来表示您的业务对象,存在不同的理念(有些好,有些坏)。我针对上述这些哲学的核心进行了概要介绍,但 Rocky Lhotka 和 Martin Fowler 等个人对它们进行了更详细的记录。
The direction you take will most likely depend on the application and from a philosophical view, may depend on how much of an idealist or pragmatist you are. That said, I am not implying that one being an idealist or pragmatist correlates to either using EF for business objects or not – it'll simply impact your take on this.
你采取的方向很可能取决于应用程序,从哲学的角度来看,可能取决于你是多少理想主义者或实用主义者。也就是说,我并不是在暗示理想主义者或实用主义者与是否将 EF 用于业务对象相关——它只会影响您对此的看法。
As of this writing, indications by Microsoft are that EF are built to handle business logic and, right or wrong, they appear to moving more in that direction. EF is ever evolving and certain technical limitations are being lifted such that EF may eventually be used to satisfy the best of both worlds. In other words, eventually you may be able to have your cake and eat it too.
在撰写本文时,Microsoft 表明 EF 是为处理业务逻辑而构建的,无论是对还是错,它们似乎都朝着这个方向发展。EF 不断发展,某些技术限制正在被解除,因此 EF 可能最终被用来满足两全其美的要求。换句话说,最终你可能能够拥有你的蛋糕并吃掉它。
Hope this helps.
希望这可以帮助。
Off to answer a question on whether or not persistence ignorance with an ORM is ridiculous considering the purpose behind it is to manage data. :-) Sorry, I couldn't resist!
回答一个关于 ORM 的持久性无知是否荒谬的问题,考虑到它背后的目的是管理数据。:-) 对不起,我无法抗拒!
回答by Mark Cidade
The Entity framework was designed for the entity objects to be used as business objects, but you should keep in mind that the business objects will be tied to O/R technology as well as the EDM model. In EF 1.0, there wasn't any support for persistence-ignorancescenarios, but support was added in 4.0. You can implement interfaces, if you don't want to use any of their base classes.
实体框架是为用作业务对象的实体对象而设计的,但您应该记住,业务对象将与 O/R 技术以及 EDM 模型相关联。在 EF 1.0 中,没有对持久性无知场景的任何支持,但在 4.0 中添加了支持。如果您不想使用它们的任何基类,您可以实现接口。
As of .NET 3.5 SP1, they should also be usable as paramater and return types in WCF service methods without any additional code.
从 .NET 3.5 SP1 开始,它们也应该可用作 WCF 服务方法中的参数和返回类型,而无需任何附加代码。
回答by Rick
In my experience, we've used EF objects within the business layer of our application, but when we make the transition into the presentation layer through our WCF service layer, we will create view objects from the EF objects.
根据我的经验,我们在应用程序的业务层中使用了 EF 对象,但是当我们通过 WCF 服务层转换到表示层时,我们将从 EF 对象创建视图对象。
In our case, only the view is passed to the presentation layer. We do this to control how the data is presented and apply defensive validation for data coming in from the presentation layer.
在我们的例子中,只有视图被传递到表示层。我们这样做是为了控制数据的呈现方式,并对来自表示层的数据应用防御性验证。
In the case of ueing EF objects in the WCF transaction, you'll lose the object context that the EF object was associated. There are some efforts in CodePlex that try to help with this but I havn't kept up with their efforts.
在 WCF 事务中使用 EF 对象的情况下,您将丢失与 EF 对象关联的对象上下文。CodePlex 中有一些努力试图帮助解决这个问题,但我没有跟上他们的努力。
回答by ChrisHDog
Two limitations to be aware of that I have run into are:
我遇到的两个需要注意的限制是:
Inherited Objects cannot have Navigation Properties - i.e. if you have a "person" class and then a "customer" and "supplier" those customer and suppliers cannont have Navigation properties.
Methods and Calculated Fields (anything in the partial classes) are not transmitted over ADO.Net Data Services - if you are also using ADO.Net Data Services anything you expand the Entity Framework objects on in partial classes will not be transmitted over ADO.Net Data Services.
继承的对象不能具有导航属性 - 即如果您有一个“人”类,然后是“客户”和“供应商”,那么这些客户和供应商就不能具有导航属性。
方法和计算字段(部分类中的任何内容)不会通过 ADO.Net 数据服务传输 - 如果您还使用 ADO.Net 数据服务,则您在部分类中扩展实体框架对象的任何内容都不会通过 ADO.Net 传输数据服务。
These are generally not show-stopper items (for navigation properties we just don't use inheritance on entity framework, for now), but might be something of interest to yourself. I'm holding out hope that a future release will enable both of these items.
这些通常不是显示停止项(对于导航属性,我们现在只是不在实体框架上使用继承),但可能是您自己感兴趣的东西。我希望未来的版本能够启用这两个项目。
回答by AndreasKnudsen
Can't you just re-attach the objects if they lose their original object context? You'd need to handle concurrency-issues yourself though.
如果对象丢失了原始对象上下文,您就不能重新附加它们吗?不过,您需要自己处理并发问题。
I wouldn't recommend using EF objects as DataContract objects for WCF, as you'd tie very strongly your implementation of entity objects to web service clients, change will be hard to do in the future, harder the more clients you plan on having.
我不建议将 EF 对象用作 WCF 的 DataContract 对象,因为您会将实体对象的实现与 Web 服务客户端紧密联系起来,将来很难进行更改,您计划拥有的客户端越多,就越难。
回答by jbe
The BookLibrary sample application of the WPF Application Framework (WAF)shows how the Model-View-ViewModel (MVVM) pattern can be used in combination with the Entity Framework.
WPF 应用程序框架 (WAF)的 BookLibrary 示例应用程序展示了如何将模型-视图-视图模型 (MVVM) 模式与实体框架结合使用。

