Accessing Entity Framework In Class Library From ASP.NET Core Web App

asp.net-core asp.net-mvc c# entity-framework entity-framework-6

Popular Answer

The whole codebase configuration for EF models and the method for providing the connection strings at runtime are shown below. Due to the difficulty in finding documentation on this, I recently battled with it as well.

Assuming your model was created using your database (DB-First): MyEntities.edmx

In your project, you'll have a little class like this:

public partial class MyEntities : DbContext
{
    public MyEntities ()
        : base("name=MyEntities")
    {
    }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        throw new UnintentionalCodeFirstException();
    }

    public virtual DbSet<MyTable> MyTable { get; set; }
}

If you chose to store the connection string in the config file when you developed your model in Visual Studio, automatic code generation will place the connection string config name in the constructor as seen above:public MyEntities(): base("name=MyEntities")

Additionally, your project's configuration will look like this:

<configuration> <connectionStrings> <add name="MyEntities" connectionString="metadata=res://MyProject/MyEntities.csdl|res://MyProject/MyEntities.ssdl|res://MyProject/MyExchangeEntities.msl;provider=System.Data.SqlClient;provider connection string='data source=SERVERADDRESS;initial catalog=DATABASENAME;persist security info=True;user id=USERID;password=PASSWORD;MultipleActiveResultSets=True;App=EntityFramework'" /> </connectionStrings> </configuration>

Now to get around this, look at the constructor for the DbContext:public DbContext(string nameOrConnectionString); Actually, it states that the connection string can be passed directly to it.

Therefore, all you have to do is add a constructor that accepts a connectionstring to this partial class and extend it.

public partial class MyEntities
{
    /// <summary>
    /// This constructor allows us to pass connection strings at runtime
    /// </summary>
    /// <param name="connectionString">Entity Framework connection string</param>
    public MyEntities(string connectionString) : base(connectionString)
    {

    }
}

Although it should go without saying, I'd want to point out that we extend the partial class rather than changing the automatically formed one to prevent it from being overwritten when we re-generate the model in the future.

Simply build your object as follows to connect using your connection string:new MyEntities("metadata=res://MyProject/MyEntities.csdl|res://MyProject/MyEntities.ssdl|res://MyProject/MyExchangeEntities.msl;provider=System.Data.SqlClient;provider connection string='data source=SERVERADDRESS;initial catalog=DATABASENAME;persist security info=True;user id=USERID;password=PASSWORD;MultipleActiveResultSets=True;App=EntityFramework'");

Finally, you can do it like this if you wish to include the EF setup in the codebase as well:

/// DbConfiguration belongs to System.Data
public class EntityFrameworkConfig : DbConfiguration
{
    public EntityFrameworkConfig()
    {
        //We set configurations for entity framework here so that we don't have to add it in the app.config
        this.SetDefaultConnectionFactory(new SqlConnectionFactory());
        this.SetProviderServices(SqlProviderServices.ProviderInvariantName, SqlProviderServices.Instance);
    }
}

/// <summary>
/// This class with the DbConfigurationType attribute allows EntityFramework to know    
/// to get its config from the EntityFrameworkConfig class instead of the app.config
/// </summary>
[DbConfigurationType(typeof(EntityFrameworkConfig))]
public partial class MyEntities
{
    /// <summary>
    /// This constructor allows us to pass connection strings at runtime
    /// </summary>
    /// <param name="connectionString">Entity Framework connection string</param>
    public MyEntities(string connectionString) : base(connectionString)
    {

    }
}
3
2/23/2017 9:14:30 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow