c# - 为什么 EF 4 中的 Persistence Ignorant POCO 需要 "Fixup"?

标签 c# entity-framework-4 poco

Entity Framework 4 备受期待的功能之一是能够以无持久性的方式使用 POCO(普通旧 CLR 对象)(即,它们“不知道”它们是通过 Entity Framework 与一些其他机制)。

我正在努力思考为什么有必要在我的“普通”业务对象中执行关联修复并使用 FixupCollection。该要求似乎暗示业务对象毕竟不能完全忽略持久性机制(事实上,“修复”一词听起来像是需要修复/更改某些内容才能与所选的持久性机制一起工作)。

具体来说,我指的是由 ADO.NET POCO 实体生成器生成的 Association Fixup 区域,例如:

    #region Association Fixup

    private void FixupImportFile(ImportFile previousValue)
    {
        if (previousValue != null && previousValue.Participants.Contains(this))
        {
            previousValue.Participants.Remove(this);
        }

        if (ImportFile != null)
        {
            if (!ImportFile.Participants.Contains(this))
            {
                ImportFile.Participants.Add(this);
            }
            if (ImportFileId != ImportFile.Id)
            {
                ImportFileId = ImportFile.Id;
            }
        }
    }

    #endregion

还有FixupCollection的使用。其他常见的不了解持久性的 ORM 没有类似的限制。

这是由于 EF 中的基本设计决策造成的吗?即使在更高版本的 EF 中,是否仍存在某种程度的非无知?有没有一种聪明的方法可以对 POCO 开发人员隐藏这种持久性依赖性?

这在实践中是如何实现的,端到端的?例如,我知道最近才添加了对 ObservableCollection 的支持(这是 Silverlight 和 WPF 所需要的)。与 EF 兼容的 POCO 对象的设计要求在其他软件层中是否存在问题?

最佳答案

找到了一些解释 - 检查它们!

POCO Template Code Generation Options (EF 团队博客)

Fixup

A fixup method is written for every navigation property on an entity and is called from the setter of the navigation property whenever its value changes. Its purpose is to ensure that each end of a bidirectional relationship stays in sync with the other. For example, in a one-to-many relationship between Cutomer and Order, whenever Order.Customer is set, the fixup method ensures that the Order is in the Customer’s Orders collection. It also keeps the corresponding foreign key property viz. Order.CustomerID in sync with the new Customer’s primary key (ID) value. This logic can be useful if the POCO entities are used independently of the EF stack, like for writing tests against them which don’t hit the database. Fixup ensures that the object graph is connected in the same way as you would expect while using them with EF. Fixup methods are a bit complex to write and hence it is useful to have them auto-generated if you are planning on using the entities in an EF independent scenario.

同时查看这个 POCO in the Entity Framework Part 1其中还有一些部分介绍了修复是什么以及它们需要做什么。

关于c# - 为什么 EF 4 中的 Persistence Ignorant POCO 需要 "Fixup"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2945278/

相关文章:

asp.net-mvc-3 - 正在延迟加载为 null 的急切加载的相关对象

c# - 使用linq计算平均值而不分组

c# - 单元测试与集成测试 : Entity Framework Core In memory

entity-framework - Entity Framework 4 SaveChanges 不起作用并且没有抛出任何错误?

c# - 在 Entity Framework 6.1 中添加存储过程的问题

c# - 从表中查询数据时管理实体的最佳实践?

nhibernate - 代码生成器不好吗?

c# - 使用参数调用存储过程时遇到问题

c# - 通过 COM 从 Delphi 触发 .NET DLL 中的事件的问题

c# - ASP.NET WebAPI 2 嵌套 JSON