I am at the beginner level of learning MVC5 using EF6. Basically I am trying to use a connection string defined in machine.config rather than using web.config whilst creating the ADO.NET Entity Data Model. The reason why I am using machine.config for connection string is; we have different SQL Cluster servers and application servers. On local machine we use local SQL Server instance but on beta/Live SQL server we use different instance names. The credentials are different too. so on each application/web server we have defined the ConnectionString in machine.config for the same database name but with different credentials.
Is there a way I can use ConnectionString specified in machine.config whilst using the wizard to create ADO.Net Entity Data Model or can I give reference of machine.config ConnectionString to my app web.config or is there any other way to solve this problem?
I am using Database First technique using MVC5. I have tried the following after creating edmx by using local DB and then tried to change the connection string in my context class:
public partial class MasterDataEntities : DbContext
{
public MasterDataEntities()
: base(string.Format("{0}", getConnectionString()))
{
}
public static string getConnectionString()
{
Configuration config = ConfigurationManager.OpenMachineConfiguration();
return config.ConnectionStrings.ConnectionStrings["masterdata"].ConnectionString;
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
throw new UnintentionalCodeFirstException();
}
}
Error: OnModelCreating
Additional information: Code generated using the T4 templates for Database First and Model First development may not work correctly if used in Code First mode. To continue using Database First or Model First ensure that the Entity Framework connection string is specified in the config file of executing application. To use these classes, that were generated from Database First or Model First, with Code First add any additional configuration using attributes or the DbModelBuilder API and then remove the code that throws this exception.
Kind Regards
You can simply define your connection string in machine.config. When you use the configuration manager it will look in the machine.config first for your appsettings and then your application config file.
Check this article on Configuration files
string innerConnectionString = ConfigurationManager.ConnectionStrings["Inner"].ConnectionString;
<add name="Inner" connectionString="Data Source=SomeServer;Initial Catalog=SomeCatalog;Persist Security Info=True;User ID=Entity;Password=SomePassword;MultipleActiveResultSets=True" providerName="System.Data.SqlClient" />
After several experiments on the MVC and EF Database First approach, I found that the problem was in the machine.config's connection string. Entity Framework doesn't like the standard connection string. Connection String must have the metadata Info about the DBContext resources and the provider name for EF. My standard ConnectionString in the machine.config was:
<add name="masterDataConnectoinString" connectionString="Data Source=Instance1;Initial Catalog=masterData;Integrated Security=True;"/>
Then I copied the ConnectionString from web.config to maching.config which was created by default when I added the Entity Data Model (edmx):
<add name="masterDataConnectionString" connectionString="metadata=res://*/Models.DBContext.csdl|res://*/Models.DBContext.ssdl|res://*/Models.DBContext.msl;provider=System.Data.SqlClient;provider connection string="data source=Instance1;initial catalog=masterData;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
And then specifying the connectionstring name to be used as I have shown in my question for MasterDataEntities, solves the problem.
Using machine.config's ConnectionString creates another issue. If you amend the database, e.g add another column into any table and would like to update the Entity Data Model (edmx) with the new change, you right click the edmx Diagram and then click Update Model from Database, which will not work. The wizard will ask you to specify the new connection, which is not right. It should offer you to Add/Refresh/Delete tables or views or procedures.
To solve this problem temporarily I kept the connectionString into my web.config but commented out. If I had to update the model from the database, uncomment the web.config connectionString and set back your (in my case) MasterDataEntities to use web.config:
public partial class MasterDataEntities : DbContext
{
public MasterDataEntities()
: base("name=masterDataConnectionString"))
{
}
}
Which updates the model. If anyone got a better solution please please let me know. Thanks
Related
I have a azure V1 function using a project dll that handles entity framework.
First I set connect string like
metadata=res://*/Dev.csdl|res://*/Dev.ssdl|res://*/Dev.msl;
provider=System.Data.SqlClient;
provider connection string='
data source={IP};initial catalog={DBName};
persist security info=True;
user id={User};password={PW};
MultipleActiveResultSets=True;
App=EntityFramework'
and I got
Keyword not supported: 'metadata'.
then I changed my connect string to
data source={IP};initial catalog={DBName};persist security info=True;user id={User};password={PW};
and I got
The context is being used in Code First mode with code that was generated from an EDMX file for either Database First or Model First development. This will not work correctly. To fix this problem do not remove the line of code that throws this exception. If you wish to use Database First or Model First, then make sure that the Entity Framework connection string is included in the app.config or web.config of the start-up project. If you are creating your own DbConnection, then make sure that it is an EntityConnection and not some other type of DbConnection, and that you pass it to one of the base DbContext constructors that take a DbConnection. To learn more about Code First, Database First, and Model First see the Entity Framework documentation here: http://go.microsoft.com/fwlink/?LinkId=394715
And here's my code
DevEntities db = new DevEntities();
var lstAcAccount = db.AcAccounts.ToList();
return req.CreateResponse(HttpStatusCode.OK, lstAcAccount);
DevEntities is from other dll project that using the connect string above.
So, what should I do to make this work?
You shouldn't use generated connection string, now you have all metadata files included in your solution. Instead try use in connection string section of app.config:
"data source=localhost\sqlexpress; initial catalog=sample; integrated security=True;MultipleActiveResultSets=True;"
If it is Database first:
Open the .edmx[Diagram] -> right click -> "Update Model from database"
And see if the will appear the "Add", "Refresh" and "Delete" tabs.
If doesn't... probably your connection is broken and the dialog for VS creates a new connection string will appear instead.
Hope it helps.
I've been looking through questions on here but have yet to come across anything that deals with my problem, apologies if this is a duplicate and I've missed something.
I have an ASP.Net MVC project with Entity Framework Code First.
In my Dbcontext I have;
public Context() : base("DatabaseName")
{
System.Data.Entity.Database.SetInitializer(new MigrateDatabaseToLatestVersion<Context, Configuration>());
}
In my web config I have;
<connectionStrings>
<add name="DatabaseName" connectionString="connsection string is here"/>
</connectionStrings>
When my application is deployed, I get the error
'CREATE DATABASE permission denied in database 'master'.' as soon as
it tries to access the Context for the first time.
What I don't understand is how to stop it trying to create a database and just use the connection string that I have given it. The database already exists (It's on shared hosting so I don't have much control over it) and I know the connection string is correct as I have Hangfire installed in the same application, using the same connection string and it has successfully created the tables but for some reason EF doesn't create the tables in the database and instead tries to create one, which it cannot do.
Entity Framework is installed in the same project as the config file, in fact, it's a single project application.
I've tried creating another database and adding a second connection string in case Hangfire was preventing EF from using it but had the same issue. I've also tried putting the full connection string directly into :base("") on the context, but it has no effect.
try getting connectionString by name
public Context()
:base("name=DbConnection")
{
}
in Web.config file add
<connectionStrings>
<add name="DbConnection" connectionString="Data Source=serveraddress;Persist Security Info=False;User ID=usename;Password=pass;Initial Catalog=databasename" providerName="System.Data.SqlClient" />
</connectionStrings>
Everything works great when I run my project locally, but when I deploy to Azure I get the following error.
"Code generated using the T4 templates for Database First and Model First development may not work correctly if used in Code First mode. To continue using Database First or Model First ensure that the Entity Framework connection string is specified in the config file of executing application. To use these classes, that were generated from Database First or Model First, with Code First add any additional configuration using attributes or the DbModelBuilder API and then remove the code that throws this exception."
My connection string is:
add name="LifeEntities" connectionString="Server=tcp:abc000000ab.database.windows.net,1433;Database=Life;User ID=myid#abc000000ab;Password=mypw;Trusted_Connection=False;Encrypt=True;Connection Timeout=30;" providerName="System.Data.SqlClient"
I'm getting this error when my code tries to open the context of my entity framework database. Note, that I'm using a pretty basic MVC project template that does ASP.NET Identity as well.
I've read that this is because of code first vs data but not sure how to solve this issue.
That's a pure SQL connection string. You need to use a EF connection string, including the model metadata etc.
Here's an example:
<add name="Context" connectionString="metadata=res://*/Context.csdl|res://*/Context.ssdl|res://*/Context.msl;provider=System.Data.SqlClient;provider connection string="data source=.;initial catalog=Context;integrated security=True;MultipleActiveResultSets=True;"" providerName="System.Data.EntityClient" />
I have gone through the steps to publish my web app using database first on the azure portal.
However, when I publish I get this error message:
Code generated using the T4 templates for Database First and Model
First development may not work correctly if used in Code First mode.
To continue using Database First or Model First ensure that the Entity
Framework connection string is specified in the config file of
executing application. To use these classes, that were generated from
Database First or Model First, with Code First add any additional
configuration using attributes or the DbModelBuilder API and then
remove the code that throws this exception.
My connection string in the web.config after it has been modified by publish:
<add name="MySiteEntities" connectionString="metadata=res://*/MySite.csdl|res://*/MySite.ssdl|res://*/MySite.msl;provider=System.Data.SqlClient;provider connection string="data source=tcp:**********.database.windows.net,****;initial catalog=MySite;user id=username#**********;password=*******;MultipleActiveResultSets=True"" providerName="System.Data.EntityClient" />
My context (generated by edmx):
public partial class MySiteEntities : DbContext
{
public MySiteEntities()
: base("name=MySiteEntities")
{
}
...
I am very confused becuase it seems like entity framework is trying to use code first rather than database first.
UPDATE:
I just tried using the same connection string locally and the web app seems to run fine. The web app does connect to the remote database fine. It is only when I publish to azure it fails.
Read my answer to a similar question at Entity framework work locally but not on azure.
If you made the same "mistake" I did, this is what's happening ... the Azure-deployed app isn't finding your connection string "MySiteEntities" inside your web.config. Instead, at the time your created your Azure Web Site (or Cloud Service or whatever), you created an associated Azure SQL Database and gave its connection string the exact same name, "MySiteEntities". This latter connection string is a "plain" connection string without Model/Database-first metadata references, and so is being treated as a Code-First connection by EF, which then complains about the conflict. See Code First vs. Database First for an explanation of this distinction.
It should be:
<connectionStrings>
<add name="MyDatabaseModelEntities"
connectionString="metadata=res://*/MyDBModel.csdl|res://*/MyDBModel.ssdl|res://*/MyDBModel.msl;
provider=System.Data.SqlClient;
provider connection string="
Data Source=<provideServerName>.database.windows.net;
Initial Catalog=MyDatabase;
Integrated Security=False;
User ID=<provideUserID>;
Password=providePassword>;
MultipleActiveResultSets=True;
Encrypt=True;
TrustServerCertificate=False""
providerName="System.Data.EntityClient"/>
</connectionStrings>
I changed connection string to remote (Azure) on my local web.config, then remove all set connection strings during publishing and publish web.config. It rewrites remove web.config. Then return connection string on local web.config to local connection. It works fine now.
I'm just starting to learn C# and ASP.NETMVC, but every example I've found puts the database in the App_Data folder. I don't want to do this.
I'd like to create a new version of Nerd Dinner and move the connection string to the web.config, but I can't find any examples on how to do it. My database is called NerdDinner and I'm using SQL Server Express.
What's the correct syntax to add the new connection string to my web config? Does this have any effect on creating LINQ to SQL classes?
I always go to http://www.connectionstrings.com/ when I forget how a connectionstring is written.
Standard security SQL Server 2008
Data Source=myServerAddress;Initial Catalog=myDataBase;User Id=myUsername;Password=myPassword;
Here is an article on MSDN talking about How to: Read Connection Strings from the Web.config.
You have a section almost at the top in your Web.config called connectionstrings, it could look something like this:
<connectionStrings>
<add
name="NorthwindConnectionString"
connectionString="Data Source=serverName;Initial
Catalog=Northwind;Persist Security Info=True;User
ID=userName;Password=password"
providerName="System.Data.SqlClient"
/>
</connectionStrings>
I would recommend however that you also look in to Entity Framework which is an abstraction between your code and the database, it makes it easier to work with "objects" in your database. You can find an introduction to ADO.NET Entity Framework here. But first of all you should focus on getting your connection up and running to your database using the information at the top.
An additional way to have your context 'point' to the connextionsStrings line in the web.config file is to try this constructor.
public class MainDB : DbContext
{
public MainDB() : base ("name=DefaultConnection")
{
}
public DbSet<User> Users { get; set;}
}
Then change the name to DefaultConnection in the web.config file.