Karl
Karl

Reputation: 6832

Creating multiple Entity Framework EDMX files for factory pattern use

People are doing clever things with Entity framework, but I think I'm doing something quite simple, and can't seem to get it going.

I have two separate databases. Database A and database B.

I need to create contexts to these databases separately, so I want a factory pattern that will instantiate either context for me. I am trying to use a database first approach.

I referenced Entity Framework via the Nuget package manager, and created a new item using Visual Studio. The only item with an EDMX extension to choose from was "ADO.NET Entity Data Model", so I've gone with that and selected database A.

The EDMX file has been generated, and I can see my entities. When it comes to accessing them programmatically, the entities have been dumped into the default namespace. This means that I get intellisense for the entity by going to my.namespace.datasource.TableA.

If I now create another EDMX file in the same area, the same entites will be dumped into the same place, and I'll get conflicts.

An example of the error I get is:

"The type 'my.namespace.datasource.Entities' already contains a definition for 'TableA'"

Why is this? Why isn't it creating a default namespace for that EDMX file that the entities will reside within? How can I have multiple EDMX files working in harmony and providing separate contexts when I need them?

Any help's appreciated!

Cheers,

Karl.

Upvotes: 2

Views: 2659

Answers (1)

Dennis
Dennis

Reputation: 37770

  • Option 1. Select model project item in solution explorer, go to item properties, set the property "Custom Tool Namespace" to the preferred value. Your generated code will be put in the namespace you've set.
  • Option 2. Create two separate folders and put one model into the first folder, and one - into the second folder.
  • Option 3. Put your models into separate projects.

Note. If you're using VS2010 and any T4 generator (e.g., DbContext generator), you should:

  • turn off default code generation by clearing "Custom tool" property for EDMX project items;
  • set "Custom Tool Namespace" for T4 project items (e.g. Model1.tt and Model1.Context.tt).

Upvotes: 3

Related Questions