Search code examples
c#entity-frameworkfactory-pattern

Entity Framework and Factory Pattern


I'm attempting to implement the factory pattern with Entity Framework, but Entity Framework seems to call the default ctor and setters of each member whether they are private, or not.

Is there any way to get Entity Framework to call my Object.Create() instead?

Edit:
This is a simplified example of my class. I need entity framework to call the static Create() instead of the ctor.

public class Foo
{
    public Name { get; set; }
    public static Foo Create()
    {
        var newFoo = new Foo();
        newFoo.Init();
        return newFoo;
    }
    public void Init()
    {
        Name = "You know, on second thought, I want the name to be this instead.";
    }
    private Foo()
    {
        Name = "Hello Stack Overflow!";
    }
}

Solution

  • First, you could instead try searching for how to resolve or Entities injection IoC or similar - as that's requested more often, and basically need the same solution.

    And second, usually (but not necessarily) what you're trying to do suggests a bit awkward design and could paint you into problems later on - actually, to me it suggests that you should seek different approach. Entities, POCO are not designed (again normally, it doesn't mean there isn't a case that warrants it) to be used in such way, and there're ways to work around such use. Let the EF create and deal with them, and try to extract that initialization into some form of repository or something. My suggestion at least...

    Entity constructor is invoked internally (whether private or not) and as far as I know, even the latest EF 6 doesn't provide means for that. EF 6 has the IDbDependencyResolver but doesn't help in your case.

    But what you could do is to 'inject into the object initialization' process I think - also mentioned by Ladislav Mrmka in a similar context here IOC with Entity Framework

    You need to obtain the ref to ObjectContext as in:

    var objectContext = ((IObjectContextAdapter)db).ObjectContext;

    ...and then use the objectContext.ObjectMaterialized where the ObjectMaterializedEventArgs argument of the event has the Entity object.

    You need to do additional casting there based on your type to get to the entity of yours.

    I haven't worked with that for a while but might work what you need.