IngoB
IngoB

Reputation: 1

Entity Framework 6.0: how to use edmx context when connection is configured in code?

I use Visual Studio 2013, Entity Framework 6.0. So far I had the connection string in the app config, and that worked. The DB context was created by adding a "ADO .Net Entity Data Model" with the option "EF designer from database" But now I need to move it to code since it will depend on user input.

I followed this example for the connection string and my DB successfully connects http://msdn.microsoft.com/library/vstudio/bb738533

But now I need to use the connection with my database context, and I can't get this done. Say my data model is named MyDB, then I had under MyDB.edmx the MyDB.Context.cs, and there the MyDBEntities class derived from DbContext.

I re-created the data model, but this time did not select the option to store the connection string in the app config. First difference in result is that MyDBEntities is now only called Entities. Why that?

I see that the DbContext has a constructor which accepts a EntityConnection. I was able to create a DbContext with the connection, but that is not linked with the datatypes under MyDB.edmx. And MyDBEntities ( or just Entities after the change ) has no constructor accepting an EntityConnection.

So how can I use the generated edmx model but configure/open the connection at runtime?

Upvotes: 0

Views: 301

Answers (1)

IngoB
IngoB

Reputation: 1

Found it. Ok so in EF 6.0 the DbContext no longer has a constructor that accepts a connection, but there is one that accepts a connection string.

Just modify the generated code and add the following constructor:

public Entities(String connectString) : base(connectString) { }

Then directly pass the connection string and it will work.

Upvotes: 0

Related Questions