自定义实体实现 [英] Custom entity materialization

查看:88
本文介绍了自定义实体实现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用EF6是否可以注入自定义对象实例创建者?
我需要做的是在实体化发生之前向EF提供实体实例。

Is there a way, with EF6, to inject a custom object instance creator? What I need to do is to provide instances of entities to EF before the matrialization occurs.

基本上,我希望能够使用非无参数构造函数,以便能够使用DI聚合,最后使用EF持久化。

basically I want to be able to define my POCO entity with non parameterless constructor, so to be able to use DI aggreate, that in the end is persisted with EF.

我已经可以使用ObjectMaterialized事件获得类似的结果:

I've that I can achive something similar using the ObjectMaterialized event:

var oc = ( this as IObjectContextAdapter ).ObjectContext;
oc.ObjectMaterialized += ( s, e ) => 
{
   //resolve and inject dependencies here using e.g. public properties  
};

但我真的很想在构造函数上声明依赖项。

but I'd really love to have dependencies declared on the constructor.

有什么想法吗?
干杯,
.m

Any idea? Cheers, .m

推荐答案

使用默认的ObjectContext,我认为这不可能看了EF代码。最终,对象由 ObjectContext.CreateObject 创建。这将执行以下两项操作之一:它调用默认构造函数,否则,如果启用了代理创建,则会创建相关的代理类型。代理类型用于增强的更改跟踪和延迟加载属性。

Using the default ObjectContext, I don't believe this is possible having looked at the EF code. Ultimately the objects are created by ObjectContext.CreateObject. This does one of two things: It either calls a default constructor or else, if proxy creation is enabled, it creates the relevant proxy type. The proxy types are used for enhanced change tracking and for lazy loading properties.

但是, ObjectContext.CreateObject 是虚拟的,因此可以在派生类中重写它。将为该派生类提供对容器(或生存期范围)的引用,然后在重写的 CreateObject 调用中,此解析将用于解析实体。

However, the ObjectContext.CreateObject is virtual, so one could override it in a derived class. That derived class would be provided with a reference to the container (or lifetime scope) and then, in the overridden CreateObject call, this would be used to resolve the entity.

然后问题变成了,如何将派生类型指定为 ObjectContext > DbContext ?好吧,有构造函数,该构造函数采用 ObjectContext DbContext 应该使用。

The question then becomes, how does one specify a derived type as the ObjectContext to use for a DbContext? Well, there is a constructor that takes an instance of the ObjectContext the DbContext should be using.

这是我的想法开始偏离的地方,因为 ObjectContext 本身需要要告知它在其中使用的模型连接字符串。我认为这可能意味着代码优先方法将不起作用,因为该模型是延迟创建的,因此在构建 DbContext 之前不可用。但是,对于模型优先方法,也许可以行得通吗?

This is where my idea starts to go a bit off the rails, as the ObjectContext itself needs to be told about the model it is using in the connection string. I think this might mean that a code first approach would not work as the model is lazily created and thus not available prior to the DbContext being constructed. However, for a model first approach, maybe this could work?

这篇关于自定义实体实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆