Code-First change data source without connection string - c#

I seem to have an issue creating an MVC4 application where I have adopted the code-first approach to creating my models but no connection string seems to have been created in the web.config file.
The constructed database seems to have been built on (localhost)\SQLEXPRESS instance but I would like to change this to an external data source. Without a connection string to update I'm not sure how to do this.
Please could someone point me in the right direction?
EDIT: I found the following diagram which highlights what the answers have said pretty well
(source: entityframeworktutorial.net)

You have to add a connection string yourself
<add name="SomeDb" connectionString="Data Source=SERVENAME;Initial Catalog=DBNAME;User Id=loginid;Password=password" providerName="System.Data.SqlClient" />
Name of this string should match to the name of your context class.
public class SomeDb: DbContext
{
public SomeDb()
: base("name=SomeDb")
{
}
}
This should do it.

If you use ADO.NET Entity Framework(.edmx) it will update your web.config file with connection string. but in code-first you need to write your connection string in web.config like,
suppose you dbcontext looks like,
public class SampleDbContext:DbContext
{
public SampleDbContext():base("SampleDbContext")
{
}
...
...
}
after you should create your connection string in web.config with SampleDbContext name like,
Hope this helps

You have to create a connection string with the same name as your DbContext class:
<connectionStrings>
<add name="NameOfDbContext" connectionString="Data Source=ServerName\InstanceName;Initial Catalog=DatabaseName;Integrated Security=True" providerName="System.Data.SqlClient" />
</connectionStrings>
You can also specify the connection string yourself using an overload of the DbContext class:
public class MyDbContext() : base("ProductionDbContext")
{
}
Now you can use ProductionDbContext as connection string.
See this article on MSDN for more information.

Related

Entity framework error when enable migrations

I already had a database first ASP MVC project. Now I remove .edmx file and and all every thing related to database first and make it code first. When I want to Enable-Migrations I get this error in powershell. :
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
Here is my Connection string in webconfig:
<connectionStrings>
<add name="Context" connectionString="Data Source=.\;AttachDbFilename=|DataDirectory|\myDbName.mdf;Initial Catalog=myDbName;Integrated Security=True;MultipleActiveResultSets=true" providerName="System.Data.SqlClient"/>
</connectionStrings>
And Here is my Context :
public class Context : DbContext
{
public Context()
: base("name=Context")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
throw new UnintentionalCodeFirstException();
}
}
How can I resolve this problem?

How can I define SQL server connection string inside a class and use everywhere in project?

I don't want to change connection string every where in my project. I want to
share a common definition.
It is possible to do everything related to database (e.g. insert, update, delete) definee in that class?
I am using Microsoft SQL server
Create a static class dbHelper.cs and then use it throughout for insert, update, delete, etc.
See a pseudo code sample below.
public static class dbHelper
{
private static string conStr = "connection_string";
public static int insertDeleteUpdateQuery(string query)
{
// use conStr to create connection string
// open connection here
// execute your query
}
}
Use above class like this
dbHelper.insertDeleteUpdateQuery("ADO.NET query);
A posible solution in VB.Net is make a master class and make others inherit from it.
Public Class wsMaster
Inherits System.Web.Services.WebService
Protected conn As String = "CONNECTION_STRING"
End Class
Public Class wsResport
Inherits wsMaster
End Class
Or if you have a web.config add a connection string.
<connectionStrings>
<add name="conn" connectionString="Server=SERVERNAME;Database=DBNAME;User ID=USERDB;Password=USERPASS" providerName="System.Data.SqlClient"/>
</connectionStrings>
I hope helps you
Here is on of the (many) possible solutions:
You can store you connection string inside a configuration file (app.config if you're developing a desktop application or a DLL or web.config if you are developing a web service or a web application). Sample .config file:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
<add name="TestCfg" connectionString="Data Source=.;Initial Catalog=xxx;IntegratedSecurity=True" providerName="System.Data.SqlClient" />
</connectionStrings>
</configuration>
Then you can implement a DAL (Data access layer) that implements all DB-related operations (see here or here for more information)
Finally your application should always access the DB using methods exposed by the DAL

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

I m trying to migrate a project initially developed using EF4 to EF6, to take advantage of EF6 transactions management.
The problem I m facing is that the project has been created using the Database First approach, so when I m using code like context.Database.UseTransaction, I m encountering the following error:
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 exception triggers inside the OnModelCreating method of my DbContext class.
Any idea ?
Thanks
EDIT:
The thing is that it's legacy code using EDMX with database first approach. I have to implement EF6 transactions inside this project, so it should now be more like a code first pattern.
In addition, here's the context class:
public class MyContext : BaseDbContext
{
public MyContext (DbConnection existingConnection, bool contextOwnsConnection)
: base(existingConnection, contextOwnsConnection)
{
}
}
And the connection string:
<add name="CS"
connectionString="Data Source=MyServ;Initial Catalog=MyDBName;User Id=MyUser;Password=MyPwd;Pooling=True;Min Pool Size=5;Max Pool Size=20;Persist Security Info=True;MultipleActiveResultSets=True;Application Name=EntityFramework;Enlist=false"
providerName="System.Data.EntityClient" />
I tried setting the providerName to System.Data.SqlClient but it doesn't change anything.
Please note that the original connection string was in the database first format:
<add name="OrderManagement"
connectionString="metadata=res://*/MyManagementModel.csdl|res://*/MyManagementModel.ssdl|res://*/MyManagementModel.msl;provider=System.Data.SqlClient;provider connection string="Data Source=MyServer;Initial Catalog=MyDBName;User Id=MyUser;Password=MyPwd;Pooling=True;Min Pool Size=5;Max Pool Size=20;Persist Security Info=True;MultipleActiveResultSets=True;Application Name=EntityFramework""
providerName="System.Data.EntityClient" />
If I try to open a connection whilst I keep the connection string in the database first format, I m facing the exception Keyword metadata not supported, and when I put the connection string on the code first format, I m facing the error 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.
The most common mistake when converting context from database-first to code first is forgetting to remove the generated OnModelCreating. In a database-first context, OnModelCreating throws the exception:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
throw new UnintentionalCodeFirstException(); // ← throws exception
}
So take a look at your context or its base class (and their partial classes) and if it's like above code, you should remove it.
Also your code and configurations need some changes.
You are using providerName="System.Data.EntityClient" for a code first context. You should change the connection string to something like this:
<add name="MyContext" connectionString="data source=server;
initial catalog=database;User Id=user;Password=password;
multipleactiveresultsets=True;application name=EntityFramework"
providerName="System.Data.SqlClient" />
Then you should change your context constructor to something like this:
public partial class MyContext: DbContext
{
public MyContext() : base("name=MyContext") { /* . . .*/ }
// . . .
}
Also if you want to have a common base class, follow above instructions.
Note: To create code-first from an existing database, you can right click on project and choose Add New Item, then under Visual C# under Data select ADO.NET Entity Data Model and click on Add. Then from the Entity Data Model Wizard choose Code First from Database and follow the wizard. For more information see Entity Framework Code First to an Existing Database
You Have to Just Copy Connection String from App.config and Paste it into your Web.config file.
Make Sure your EDMX has updated to latest connection with database.
This works for me.
I just connection string in web.config like this
connectionString="metadata=res:///Models.wimEntities.csdl|res:///Models.wimEntities.ssdl|res://*/Models.wimEntities.msl;provider=System.Data.SqlClient;provider connection string="data source=.;initial catalog=DATABASE;persist security info=True;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient"

Application can't scaffold items

I created an MVC 5 application in VS 2013 Professional and then used EF 6.1 code first with an existing DB on SQL Server Express. When I try to create the views I’m using the “New scaffolded item…” then selecting the “MVC 5 controller with views, using Entity Framework.” I select the model and context classes and click OK. Then the following error message appears and no code is created. I’ve uninstalled EF Power Tools with the same error.
Error
There was an error running the selected code generator: ‘Exception has
been thrown by the target of an invocation.’
I've also tried uninstalling/reinstalling VS 2013 and SQL Server with no changes.
Any other ideas about what might cause this error?
In my case I moved my connection strings out of the Web.config to
<connectionStrings configSource="ConnectionStrings.config"/>
that when I started getting the error when I was trying to scaffold.
There was an error running the selected code generator: ‘Exception has been thrown by the target of an invocation.’
Moving my connection strings back to the Web.config solved my issue.
I had this problem too,
I solved the problem by calling the base.onModelCreating in my DB context
base.OnModelCreating(modelBuilder);
I had faced the same problem while creating controller using scaffold with 'ASP.NET MVC5 using views with Entity Framework'
The problem was because I provided <connectionStrings> tag before <configSections> in web.config. setting <connectionStrings> after <configSections> resolved the issue.
I guess, while scaffolding, ASP.NET MVC want to resolve the Entity Framework first, then the connection string, as I have provided connection string earlier so that after resolving the Entity Framework version it could not find the connection string so it thrown invocation problem.
This solved the issue for me,
Adding throwIfV1Schema: false to base of DbContext
As so:
public MyDbContext() : base("ConectionStringName", throwIfV1Schema: false) { }
Late reply; but, I am posting this answers with the hope that somebody can use this answer to solve their problem.
For some reason, if your program CANNOT read connectionString information (either from web.config or from other means) then, this error will be thrown.
Make sure that valid connectionString information is being retrieved properly without any problem.
I had the same error message.
I tried adding a new Data context class from the Add Controller dialog, and then I got a different error:
There was an error running the selected code generator:
'Sections must only appear once per config file. See the help topic
<locations> for exceptions.
It turns out that I had two <connectionStrings> elements in my web.config file. (I had pasted one from the app.config of the class library that contained my Entity Framework model.)
In my case, I had to revert my DBContext constructor to just using a static connection string, as defined in web.config
Scaffolding did not work when I used a dynamically created connection string.
public MyContext() : base("name=MyContext") { }
I had the same problem where it wouldn't add scaffold items it seems that uninstalling entity-framework through the nuget package manager console works
To Run Package Manager Console :
Tools -> NuGet Package Manager -> Package Manager Console
To Remove:
UnInstall-Package EntityFramework
To Reinstall:
Install-Package EntityFramework
Or in one command:
Update-Package -reinstall EntityFramework
I hope this can help someone as it took me a while to come to this.
This may help resolve your error.
In my OnModelCreating i was doing this for each entity:
modelBuilder.Configurations.Add(new EntityTypeConfiguration<EntityModel>);
When i changed it to the following i stopped getting the error you are receiving.
modelBuilder.Entity<EntityModel>();
I tried most of the above without luck.
What finally worked was:
Delete the previously dynamically created string entry
Delete my model (keeping all controllers and views)
Recreate the ADO.NET Entity Data Model - using the same name, creating a new connection string entry with the same name as before
Then everything worked again, minus 3 hours of development time.
re-add (from a backup) all of my property attributes to the table/entity classes
Seems to have something to do with the dynamically created connection string and the model. Would appreciate any thoughts on what could have happened.
In my case, I solved the issue with the connection string in the web.config.
Previuos the issue I has
<connectionStrings configSource="Configs\ConnectionString.config"/>
and I doesnt know why, but vs cant connect to the database and fail.
after the change
<connectionStrings>
<add name="UIBuilderContext" connectionString="metadata=res:/ ..... " />
</connectionStrings>
and it works
My solution was as simple as changing back the connection string name in my Web Config to DefaultConnection. Even though my dbContext has another name!
Took me 2 hours to find out this nonsense!
It seems a problem of connecting setting / inconsistent entry in via Web.config.
To fix this issue , follow below steps:
Remove connection related information (staring with <connectionStrings> from Web.config and remove models generated so far.
Now generate the model and it will add fresh connection entry in Web.config file. Once model is generated, build the solution then start doing Scaffolding controlled. it will work.
I ran into this problem too using VS 2015. I tried all the other solutions here to no success. It turned out that my connection string (although formed exactly how MS tells us to form it) needed double \ to work properly.
Here is what it was that was NOT working:
<add name="DefaultConnection" connectionString="Data Source=(LocalDb)\V11.0;AttachDbFilename=|DataDirectory|\SquashSpiderDB.mdf;Initial Catalog=SquashSpiderDB;Integrated Security=True" providerName="System.Data.SqlClient" />
and here is what I changed it to in order to get the code generator to work:
<add name="DefaultConnection" connectionString="Data Source=(LocalDb)\\V11.0;AttachDbFilename=|DataDirectory|\SquashSpiderDB.mdf;Initial Catalog=SquashSpiderDB;Integrated Security=True" providerName="System.Data.SqlClient" />
Notice the double \ characters in front of V11.0 and the database name.
Hope this saves somebody else some time.
UPDATE
This gets the code generation to work, but then the app won't run because the \V11.0 isn't a valid connection string. This looks to me like MS has a bug in their code generation when it parses the connection string. I had to change it back to a single \ after I ran the code generation to get the app working again.
UPDATE 2
After some more digging by my partner, we found out that what was really screwing up code generation was the fact that we had changed the "Initial Catalog" field. When the project was created by the Wizard, it automatically set the Initial Catalog to aspnet--. We had then changed this Initial Catalog field to be DB. This worked great for the application running. It could get to the database just fine. But for some reason this screws up the code scaffolding generation. By putting the Initial Catalog back to what it was before (the aspnet--, the scaffolding started to work again (without needing the \V11.0).
Hope that helps somebody in the future.
Check relationships between entities or other model design problem. For testing, create new class model without no relationship and use Scaffold to generate controllers and views.
Works for me.
I was getting the same error when I made some changes to my model .. Only way I was able to resolve was
1) stop/kill the process
2) clean solution and rebuild the solution
If by any chance you are following "Getting Started with Entity Framework 6 Code First using MVC 5" by Tom Dykstra.
I doubled check everything and my connection string is perfect. What I failed to realize was I copied another set of appSettings which I already have. Look below
<appSettings>
<add key="webpages:Version" value="3.0.0.0" />
<add key="webpages:Enabled" value="false" />
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
</appSettings>
My advice is to check every inch of Web.config and I'm sure that is the culprit.
In my case NuGet added the following provider to the web.config:
<provider invariantName="System.Data.SqlServerCe.4.0" type="System.Data.Entity.SqlServerCompact.SqlCeProviderServices, EntityFramework.SqlServerCompact"/>
When I changed the provider to
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer"/>
It solved the problem (costed me about 5 hours though to figure it out :-( )
I Had the same error. Here are the two things I did to fix the problem:
Added name to base in my context:
base("name=connectionstringname")
I made a mistake in myconnection string and fixed it.
It is (I'm 99% positive) a connection string issue. Once i fixed the issue in Web.Config the error went away. I was using DB first, in another project and once I copied the DB first connection string from the App.config into the web.config (using the same name) it worked as expected.
Using Visual Studio 2015
Upgraded mysql server and in the process the mysql for visual studios was upgraded from 6.9.7 to 6.9.8
In my web config there was still a reference to the old 6.9.7 version
Here is my git diff that solved the issue:
- <provider invariantName="MySql.Data.MySqlClient" type="MySql.Data.MySqlClient.MySqlProviderServices,MySql.Data.Entity.EF6,Version=6.9.7.0,Culture=neutral,PublicKeyToken=c5687fc88969c44d"></provider>
+ <provider invariantName="MySql.Data.MySqlClient" type="MySql.Data.MySqlClient.MySqlProviderServices,MySql.Data.Entity.EF6,Version=6.9.8.0,Culture=neutral,PublicKeyToken=c5687fc88969c44d"></provider>
I realize this question is old now, but I thought I'd post what solved my issue in case it helps anyone later on. In my case, it was a combination of several things mentioned in other answers. To secure my connection string I had...
Moved the connection string out of the Web.config file
Moved the server name and password to a separate file referenced in the AppSettings portion of Web.config
Used a SqlConnectionStringBuilder to put the elements together and then pass it to my context class constructor
After doing this, I was unable to create any more controllers. To fix the issue, I had to ...
Put the complete connection string back in Web.config AND remove the reference to the external connection string file
Add a parameterless constructor to my context class and give it the name of my connectionString like this:
public contextClass() : base("name=connectionStringName") { }
Rebuild the solution, and create the controller again, and it worked!
everyone. I know I'm a little late, but I think that is still valid to share my experience with this problem.
I faced this message in two projects and in both cases the problem was with the connection string.
In the first case it was "InitialCatalog" instead of "Initial Catalog" (separated).
In the second case the server name (Data Source param) was wrong.
I hope it helps.
Best regards.
For some reason when I comment the oracle.manageddataaccess.client section out between <configSections> in web.config, it worked. (VS 2015 and ODT 12)
<configSections>
<section name="entityFramework" type" />
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<!--<section name="oracle.manageddataaccess.client" />-->
</configSections>
In my case, the problem was caused by an external app settings file:
<appSettings configSource="appSettings.config" />
Bringing the app settings back into the web.config file resolved the issue.
<appSettings>
<add key="webpages:Version" value="3.0.0.0" />
<add key="webpages:Enabled" value="false" />
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
</appSettings>
I had this:
<appSettings configSource="App_Config\Server\AppSettings.config" />
<connectionStrings configSource="bin\Connections.config" />
I had to remove BOTH AND put back.
<connectionStrings>
<add name="UIBuilderContext" connectionString="metadata=res:/ ..... " />
</connectionStrings>
Removing just still caused the same error.
Using: VS 2015 Community Edition and EF 6.1.3
Implemented also: Seed method, with a personalized class, and configured in the web.config file to run every time that the model changes.
This seems to be related to some misconfiguration in the web.config file, in my case, like some of the cases I see in this post with other sections of the file, the section was repeated with different content, but it's repeated the main tag of course. The case of the section out of place, over the section, is also cause of the same behavior and narrow message while try to scaffold.
Your context class might be throwing an exception.
I was following along in the book "C# 6.0 and the .NET 4.6 Framework" and one of the last exercises of the data access layer section was to add logging. Well, I guess that blows up the scaffold wizard. Probably file permissions on sqllog.txt or HttpRuntime is not defined...who knows. When I commented all this stuff out, it worked again.
namespace AutoLotDAL.EF
{
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Data.Entity.Infrastructure.Interception;
using AutoLotDAL.Interception;
using AutoLotDAL.Models;
using System;
using System.Data.Entity.Core.Objects;
using System.Web;
public class AutoLotEntities : DbContext
{
//static readonly DatabaseLogger databaseLogger =
// new DatabaseLogger($"{HttpRuntime.AppDomainAppPath}/sqllog.txt", true);
public AutoLotEntities()
: base("name=AutoLotConnection")
{
////DbInterception.Add(new ConsoleWriterInterceptor());
//databaseLogger.StartLogging();
//DbInterception.Add(databaseLogger);
//// Interceptor code
//var context = (this as IObjectContextAdapter).ObjectContext;
//context.ObjectMaterialized += OnObjectMaterialized;
//context.SavingChanges += OnSavingChanges;
}
//void OnObjectMaterialized(object sender,
// System.Data.Entity.Core.Objects.ObjectMaterializedEventArgs e)
//{
//}
//void OnSavingChanges(object sender, EventArgs eventArgs)
//{
// // Sender is of type ObjectContext. Can get current and original values,
// // and cancel/modify the save operation as desired.
// var context = sender as ObjectContext;
// if (context == null)
// return;
// foreach (ObjectStateEntry item in
// context.ObjectStateManager.GetObjectStateEntries(
// EntityState.Modified | EntityState.Added))
// {
// // Do something important here
// if ((item.Entity as Inventory) != null)
// {
// var entity = (Inventory)item.Entity;
// if (entity.Color == "Red")
// {
// item.RejectPropertyChanges(nameof(entity.Color));
// }
// }
// }
//}
//protected override void Dispose(bool disposing)
//{
// DbInterception.Remove(databaseLogger);
// databaseLogger.StopLogging();
// base.Dispose(disposing);
//}
public virtual DbSet<CreditRisk> CreditRisks { get; set; }
public virtual DbSet<Customer> Customers { get; set; }
public virtual DbSet<Inventory> Inventory { get; set; }
public virtual DbSet<Order> Orders { get; set; }
}
}
EF 6.1 does not Support scaffolding template use EF 5
Chares

Dynamically assigning projects property name to variable within a class

I have created a class to dynamically put together SQL function statements within a project. I have found this class to be pretty useful and would like to incorporate into future projects
namespace connectionClass
{
public class connClass
{
NpgsqlConnection conn = new NpgsqlConnection(projectName.Properties.Settings.Default.ConnString);
}
}
I want to be able to dynamically input the project name without having to do it myself for every different class! the connection string will be defined within the properties settings in VS.
Any help would be greatly appreciated:)
Or simply make use of the Configuration Manager Connection Strings property:
String connStr = ConfigurationManager.ConnectionStrings["DefaultConnStr"].ConnectionString;
Then setup your app.config like so:
<configuration>
<connectionStrings>
<add name="DefaultConnStr" connectionString="Data Source=127.0.0.1..."/>
</connectionStrings>
</configuration>
One option is to have the connection class use the ConfigurationManager to get the name from the App.Config file - but this still means setting the name in there. Something like
ConfigurationManager.AppSettings["PROJECT_NAME"];
Or refactor your common code to not need a project name...

Categories

Resources