EF join string as an argument to the DbContext constructor

I saw some sample code that put a connection string with an entity as a constructor argument when creating a new DbContext. But when I added a new ADO.NET entity data model to the project (first the database), DbContext has only one constructor without parameters.

Did I miss a step? What to do to get this constructor?

Visual Studio 2012 targeting .net framework 4.5 entity structure 5.

+7
source share
4 answers

As suggested by Arthur Vickers, I am extending a partial class to have a constructor that accepts a connection string. In C # (very similar to the hege answer):

public partial class MyEFEntities { public MyEFEntities(string connectionstring) : base(connectionstring) { } } 

Or in VB.Net:

 Partial Public Class MyEFEntities Public Sub New(ConnectionString As String) MyBase.New(ConnectionString) End Sub End Class 
+8
source

The new data model wizard adds the connection string to your configuration file, and the code generation is configured to create a context using the parameterless constructor, which then calls the base constructor with the name "name = foo", so the connection string in the config file will be used.

If you want to explicitly pass the connection string to the constructor (instead of reading it from config), you can use the fact that the context is a partial class to add this constructor. You can also modify the T4 code generation template to modify the created constructor.

+4
source

if you want to change the code first, use this :)

  public class MyCustomDBContext : DbContext { public MyCustomDBContext() : base(GetConnectionStringName()) { } public MyCustomDBContext(string connString) : base(connString) { } 
+1
source

I fixed this to work with EF4 by changing the "Code Generation Strategy" to "Legacy ObjectContext"

enter image description here

0
source

All Articles