EF connection string as DbContext constructor argu

2019-01-26 11:03发布

问题:

I have seen some code sample that put an entity framework connection string as a constructor argument when creating a new DbContext. But when I added a new ADO.NET entity data model into a project (database first), the DbContext only has one parameterless constructor.

Did I miss a step? What should I do to get that constructor?

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

回答1:

As per Arthur Vickers' suggestion, I am extending the partial class to have a constructor that accepts connection string. In C# (very similar to hege's 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


回答2:

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

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



回答3:

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

    public class MyCustomDBContext : DbContext
    {
        public MyCustomDBContext()
           : base(GetConnectionStringName())
        {

        }

        public MyCustomDBContext(string connString) : base(connString)
        {

        }


回答4:

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