different way to connect with entity framework

2019-09-20 08:27发布

问题:

It's there another way about how can I made the database connection with entity framework instead the use of connection string in the web.config. Maybe passing the parameters to the modelBuilder or to the DBContext????

回答1:

I do believe that you can pass connection string in the parameter to the DataContext. What have you tried? Why do this? check out this link



回答2:

this may be useful: in the source of MyEntities:

public partial class MyEntities : ObjectContext
{
    #region Constructors

    /// <summary>
    /// Initialize a new MyEntities object.
    /// </summary>
    public MyEntities(string connectionString) : base(connectionString, "MyEntities")
    {
        this.ContextOptions.LazyLoadingEnabled = true;
        OnContextCreated();
    }

    /// <summary>
    /// Initialize a new MyEntities object.
    /// </summary>
    public MyEntities(EntityConnection connection) : base(connection, "MyEntities")
    {
        this.ContextOptions.LazyLoadingEnabled = true;
        OnContextCreated();
    }
#endregion
....

EDIT according to this Q&A my EF 4 (4.1.10331.0)

and here how it look like my web.config for EF:

<add name="MyEntities" connectionString="metadata=res://*/Models.MyModel.csdl|res://*/Models.MyModel.ssdl|res://*/Models.MyModel.msl;provider=System.Data.SqlClient;provider connection string=&quot;Data Source=.\SQLEXPRESS;Initial Catalog=MyDb;Integrated Security=True;MultipleActiveResultSets=True&quot;" providerName="System.Data.EntityClient" />

I hope this helps better



回答3:

See the third post in this thread:

http://social.msdn.microsoft.com/Forums/is/adodotnetdataservices/thread/2eb0e7a8-10c5-4c6c-80b8-23cb39161345

protected override AdventureWorksEntities CreateDataSource()
    {
        EntityConnection entityConnection = new EntityConnection();
        entityConnection.ConnectionString = "ConnectionStringConnecting to the  databaseName";
        //set other proeprties on the entityConnection
        AdventureWorksEntities dataContext = new AdventureWorksEntities(entityConnection);
        return dataContext;
     }