Search code examples
entity-frameworkdynamic-dataobjectcontextmetamodel

Dynamic Data with multiple Entity Framework models


I am using Dynamic Data with Entity framework models. If I use this with 1 EF model, then this works like a charm.

But now I need to use multiple EF models in my Dynamic Data Project and I'm receiving errors during the registration process.

Code:

    public static void RegisterRoutes(RouteCollection routes)
    {
        var model1 = new MetaModel();
        model1.RegisterContext(() =>
        {
            return ((IObjectContextAdapter)new Model1Entities()).ObjectContext;
        }, new ContextConfiguration() { ScaffoldAllTables = true });

        routes.Add(new DynamicDataRoute("model1/{table}/{action}.aspx")
        {
            Constraints = new RouteValueDictionary(new { action = "List|Details|Edit|Insert" }),
            Model = model1
        });


        var model2 = new MetaModel();
        model2.RegisterContext(() =>
        {
            return ((IObjectContextAdapter)new Model2Entities()).ObjectContext;
        }, new ContextConfiguration() { ScaffoldAllTables = true });

        routes.Add(new DynamicDataRoute("model2/{table}/{action}.aspx")
        {
            Constraints = new RouteValueDictionary(new { action = "List|Details|Edit|Insert" }),
            Model = model2
        });
    }

On runtime I'm receiving an error when he's executing model2.RegisterContext .

Error:

Item has already been added. Key in dictionary: 'System.Data.Objects.ObjectContext' Key being added: 'System.Data.Objects.ObjectContext'

So for model1 he can register the context but for model2 he's blocked on this error.

If you know how to solve this, please advise!


Solution

  • I got it to work in 2 steps:

    • by removing the '.tt' files in my entity model.
    • in your edmx model, putting the property 'Code Generation Strategy' to 'Default' of your model. (and rebuild your solution)

    After this he accepted the registration of multiple entities.