I have my API hosted on Azure and in api's WebConfig I have connection string to azure database
<add name="FilmNetConnectionString" connectionString="Data Source=filmnet.database.windows.net;Initial Catalog=filmnetDb;User ID=sa;Password=password;" providerName="System.Data.SqlClient" />
I have defined my database initializer and I want to initialize my azure database. I have tried to initialize that way however it is not working my azure database is still empty
public class FilmNetContext : DbContext
{
public FilmNetContext() :
base("FilmNetConnectionString")
{
Database.SetInitializer<FilmNetContext>(new FilmNetDbInitializer());
Database.Initialize(true);
}
how can I seed my database?
Add the initialiser to the Application_Start method in your global.asax file. That should do the trick.
Related
I have an ASP.NET Core application running as a Windows Service. Due to project requirements, I am using Entity Framework v6.3 (as opposed to using EF Core).
I am having trouble retrieving the correct connection string when performing a migration and also upon publishing the service to a server. When running the service locally, the connection string is retrieved successfully.
As I understand it, Entity Framework 6 is supposed to retrieve connection strings from web.config or app.config files, right? Therefore, I have an app.config file containing two connection strings, e.g.
<connectionStrings>
<add name="DataContext" providerName="System.Data.SqlClient" connectionString="Server=localhost\SQLEXPRESS;[redacted]" />
<add name="CrmContext" providerName="System.Data.SqlClient" connectionString="Server=localhost\SQLEXPRESS;[redacted]" />
</connectionStrings>
In my Startup class, I have registered both database contexts, e.g.
services.AddTransient<DataContext>();
services.AddTransient<CrmContext>();
On a Razor page, when I instantiate both data contexts on my local machine I can see the correct connection string is being resolved for both contexts (by using _crmContext.Database.Connection.ConnectionString).
When I attempt to add a migration using the update-database command on my CrmContext (automatic migrations enabled), the correct connection string isn't resolved. Instead, it defaults to creating a LocalDB database using the default connection string: (localdb)\MSSQLLocalDB
How come it isn't using the connection string I have provided in my app.config file? I also a web.config file but it doesn't resolve from there either.
CrmContext.cs
public class CrmContext : DbContext
{
public CrmContext() : base("CrmContext")
{
Database.SetInitializer<CrmContext>(null);
}
public IDbSet<CustomerDetails> CustomerDetails { get; set; }
}
CrmConfiguration.cs
internal sealed class CrmConfiguration : DbMigrationsConfiguration<CrmContext>
{
public CrmConfiguration()
{
AutomaticMigrationsEnabled = true;
}
protected override void Seed(CrmContext context)
{
...
context.SaveChanges();
}
}
I've tried to explicitly update the CRM connection by specifying my CrmConfiguration file:
update-database -ConfigurationTypeName CrmContext
When I do this, it creates and updates the LocalDB database instead of using my connection string.
I've also tried to explicitly referencing the connection string:
update-database -ConnectionStringName "CrmContext"
This results in this error:
No connection string named 'CrmContext' could be found in the
application config file.
My CrmContext class exists within my ASP.NET Core windows application where my DataContext class exists in a separate 'Data' project (as it's shared with an ASP.NET MVC v5 application)
When I publish my service and install the application as a Windows Service, I found that it also doesn't pick up the connection strings at all from any of the config files - it again just looks for the default localdb database. As I understand, it should pick it up from my PaymentBatchProcessorService.exe.config file, right?
My PaymentBatchProcessorService.exe.config file looks like this:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<connectionStrings>
<add name="DataContext" providerName="System.Data.SqlClient" connectionString="redacted" />
<add name="CrmContext" providerName="System.Data.SqlClient" connectionString="redacted" />
</connectionStrings>
</configuration>
As per Microsoft documentation, it should be possible to load in the additional XML configuration files via the following code in the Program.cs file, but EntityFramework still didn't pick up the connection strings:
Host.CreateDefaultBuilder(args)
.UseWindowsService()
.ConfigureAppConfiguration((hostingContext, config) =>
{
var workingDirectoryPath = Environment.GetEnvironmentVariable(EnvironmentVariables.ServiceWorkingDirectory);
config.AddXmlFile(Path.Combine(workingDirectoryPath, "app.config"));
config.AddXmlFile(Path.Combine(workingDirectoryPath, "web.config"));
})
e.g. in the above sample, the working directory path resolves to the location where my .exe is for the Windows Service.
Thanks for reading this far!
When you deploy your service, the .config file should instead be called servicename.exe.config. It should reside on the same folder where the service was registered with installutil. See Windows service app.config location.
I have multiple connection strings in Web.config (for databases that should all have the same exact schema), and my DbContext is initialized with a connection string dynamically:
public MyDbContext(string connectionStringName) : base(connectionStringName)
{
}
I do not have a default constructor for MyDbContext as it is meaningless in my case. I decide which connection string to use based on the Id value of each entity (custom sharding).
I'm trying to run enable-migrations for my DbContext, but I'm getting the following error:
The target context 'MyDbContext' is not constructible. Add a default constructor or provide an implementation of IDbContextFactory.
I've seen a sample implementation of IDbContextFactory like so:
public class MyDbContextFactory : IDbContextFactory<MyDbContext>
{
public MyDbContext Create()
{
return new MyDbContext("connectionStringName");
}
}
How is this going to help me? Isn't the connection string still hard-coded? How could I add migrations for each database?
And how about providing default constuctor for that DbContext and then when you call scripts add-migration and update-database you may use -ConnectionStringName and -ConnectionProviderName attributes to point to database you want to use.
By the way - enable-migrations script does not do much - it addes Migrations folder to your project and Configuration class. You might do it yourself.
Best Soution is to use a separate file where you will mention list of Id values against a connection e.g in
<connectionStrings>
<add name="MyConn1"
connectionString="#your connection string"
/>
<add name="MyConn2"
connectionString="#your connection string"
/>
and then in
<appSettings>
<add key="MyConn1" value="entity1,entity2" />
<add key="MyConn2" value="entity3,entity4" />
</appSettings>
Then dynamically load your connection string in some global variable
public MyDbContext() : base(MyConnectionManager.connectionStringName)
{
}
You can do it using IoC as well. Look at the sample code.
https://github.com/aamir-poswal/CodeSample
Especially
- Bootstrapper.cs
- CRMContext.cs
- DatabaseFactory.cs which you need to customize in your context
I use SQL Server developer edition and would like to use EF code first. I found many articles explaining how to work with either a localdb or SQLExpress. How do I tell my project to rather use my ..\SQL2008 instance?
I'm thinking that somewhere, somehow, one must be able to tell the project to use a specific connectionstring. But where? Adding it to my app.config file doesn't work. This is what I've tried:
<connectionStrings>
<add name="Context" connectionString="Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=TimeApp;Data Source=Amanda-PC\SQL2008; MultipleActiveResultSets=True" providerName="System.Data.SqlClient"/>
</connectionStrings>
You can specify which connection string to use by passing the name of the connection string to the DbContext.
public class YourContext : DbContext
{
public YourContext()
: base("Context")
{
}
}
See this for more information
I am using Entity Framework Code First 4.3 + Azure and having difficulties connecting to the database. The error I get is the following (on the first query):
Keyword not supported: 'server'.
I have the following connection set up in my Web.config
<configSections>
type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=4.3.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
</configSections>
<connectionStrings>
<add name="TestDBContext"
connectionString="Server=tcp:[SUBSCR].database.windows.net,1433;Database=[MyDB];User ID=[user];Password=[pass];Trusted_Connection=False;Encrypt=True;PersistSecurityInfo=True"
providerName="System.Data.EntityClient" />
</connectionStrings>
My DbContext implementing class uses the connection string's name:
public class MyContext : DbContext, IMyContext
{
public MyContext()
: base("TestDBContext")
{
Configuration.LazyLoadingEnabled = true;
Configuration.ProxyCreationEnabled = true;
}
Can you tell what is going on?
I just had the same problem.
You're missing all the metadata in the connection string that Entity Framework requires. The connection string provided by SQL Azure needs to inserted within the provider connection string parameter of EF's connection string.
<add name="MyConnectionString" connectionString="metadata=res://*/Model.Model.csdl|res://*/Model.Model.ssdl|res://*/Model.Model.msl;provider=System.Data.SqlClient;provider connection string="[PUT SQL AZURE CONN STRING HERE]"" providerName="System.Data.EntityClient" />
You'll need to use the metadata from your own project. I pulled that metadata from an EF project generating from an existing database.
I had the same problem. I solved, putting in the web.config this connectionstring:
<add name="eManagerTurModelConnection" connectionString="metadata=res://*/ORM.eManagerFinanceModel.csdl|res://*/ORM.eManagerFinanceModel.ssdl|res://*/ORM.eManagerFinanceModel.msl;provider=System.Data.SqlClient;provider connection string="Data Source=<server>.database.windows.net;Initial Catalog=eManagerTur;Integrated Security=False;User ID=<user>;Password=<Password>;Connect Timeout=15;Encrypt=False;TrustServerCertificate=False;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
And after I removed the connectionstring of my website, worked, because it was not getting the connection string that I added in my web.config.
English bad... =)
The provider should be providerName="System.Data.SqlClient"
I connected to Azure from VS and then looked at the properties and set my connection string and provider name.
<add name="context" connectionString="Data Source=myServer,myPort;Initial Catalog=myDBName;Persist Security Info=True;User ID=myUserName;Password=myPassword;" providerName="System.Data.SqlClient"/>
I was then able to run update-database with no issues.
i tried like this, it may help you. may be 1433 is making problem, is it port no ? or what? . try like this.
check this link Windows Azure with Sql
<add name="dbContext" connectionString="Server=tcp:xxxxxxxx.database.windows.net;Database=xxxxxxxx;User ID=xxxxxxx#xxxxxxxxx;Password=xxxxxxxxxx;Trusted_Connection=False;Encrypt=True;" providerName="System.Data.EntityClient" />
Try this:
Data Source=tcp:YOUR-DATABASE-HERE.database.windows.net,1433;
Database=GolfRounds;
User ID=YOUR-USERNAME#YOUR-SERVER; Password=YOUR-PASSWORD; Trusted_Connection=False; Encrypt=True;
There is also an MSDN article at http://msdn.microsoft.com/en-us/library/windowsazure/ff951633.aspx that may be helpful.
I had a similar problem where I did not have access to the metadata, in this case you need to use System.Data.SqlClient as the provider. You will also need to add MultipleActiveResultSets=True to your connection string
Can somebody tell me how I can setup my MVC3 applciation so that when it first creates a database that it does so in a local (or remote) instance of SQL Server 2008 instead of using SQL Server Express?
So if you're using EF, then you will use a class to connect such as
public class EFDbContext : DbContext
{
public DbSet<Product> Products
{
get;
set;
}
}
Now, you only need a connection string in your project's WebConfig file (not the webConfig in the Views folder). Add a connectionStrings section under the configuration node like this. NOTE: The class and the connection string must share an identical name - in this case, "EFDbContext".
<configuration>
<connectionStrings>
<add name="EFDbContext" connectionString="Data Source=SERVERNAME\;Initial Catalog=DATABASENAME;Persist Security Info=True;User ID=USERNAME;Password=PASSWORD"
providerName="System.Data.SqlClient"/>
</connectionStrings>
"SERVERNAME\" will connect you to the default installation. If you're looking for the default installation on your local machine, just enter your computer name and you're golden. If you prefer to use window authentication rather than SQL Server authentication, just substitute "Integrated Security=true" for the UserID/Pwd portion of the connection string. HTH
You can choose connection string using constructor as following way :
Public class EFDbContext : DbContext
{
public EFDbContext() : base("dbconninfo"){}
}
<configuration>
<connectionStrings>
<add name="dbconninfo" connectionString="Data Source=SERVERNAME\;Initial Catalog=DATABASENAME;Persist Security Info=True;User ID=USERNAME;Password=PASSWORD"
providerName="System.Data.SqlClient"/>
</connectionStrings>