Code first still trying to create database - c#

I get always this exception, even if Database initializer is set to CreateIfNotExists.
Additional information: Cannot create file 'C:\\Users\\Krab\\Documents\\Visual Studio 2013\\Projects\\Customer_UI\\customers2.mdf' because it already exists. Change the file path or the file name, and retry the operation.
CREATE DATABASE failed. Some file names listed could not be created. Check related errors.
Why is EF trying to create the database even if it already exists?
App.config
<connectionStrings>
<add name="Customer.CustomersContext" connectionString="Data Source=(LocalDB)\v11.0;AttachDbFilename='C:\\Users\\Krab\\Documents\\Visual Studio 2013\\Projects\\Customer_UI\\customers2.mdf';Integrated Security=True;Connect Timeout=30" providerName="System.Data.SqlClient" />
</connectionStrings>
DbContext:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.Entity;
namespace Customer
{
public class CustomersContext : DbContext
{
public CustomersContext() : base("Customer.CustomersContext")
{
Database.SetInitializer(new CreateDatabaseIfNotExists<CustomersContext>());
//Database.CreateIfNotExists();
//System.Console.WriteLine(Database.Connection.ConnectionString);
}
public DbSet<CustomerDb> Customers { get; set; }
public DbSet<Contact> Contacts { get; set; }
}
}

You don't have to escape backslashes in App.config files.
My guess is that whatever mechanism that checks for an existing database does not correctly resolve file paths with double directory separators (C:\\Users\\...).
EF would then go ahead and try to create a new database, but whatever mechanism that creates new databases does correctly resolve file paths with double directory separators. Resulting in an IOException because the file exists.
If my hunch is correct, simply unescaping the path would have fixed the problem.

Ok now it looks fine.
Changed name of connection string to another one
Removed that escaping from .mdf filename in connection string
Changed .mdf filename to another one, so i am not using the old one

The error is referring to a file on the SQL Server instance, wherever that is. In my case, it was a different machine. I had renamed the database in hopes of getting EF to recreate it

Related

Connecting to mysql database from windows forms application on another pc? [duplicate]

var connection = ConnectionFactory.GetConnection(
ConfigurationManager.ConnectionStrings["Test"]
.ConnectionString, DataBaseProvider);
And this is my App.config:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
<add name="Test" connectionString="Data Source=.;Initial Catalog=OmidPayamak;Integrated Security=True" providerName="System.Data.SqlClient" />
</connectionStrings>
</configuration>
But when my project runs this is my error:
Object reference not set to an instance of an object.
You can just do the following:
var connection =
System.Configuration.ConfigurationManager.
ConnectionStrings["Test"].ConnectionString;
Your assembly also needs a reference to System.Configuration.dll
Since this is very common question I have prepared some screen shots from Visual Studio to make it easy to follow in 4 simple steps.
string str = Properties.Settings.Default.myConnectionString;
Also check that you've included the System.Configuration dll under your references. Without it, you won't have access to the ConfigurationManager class in the System.Configuration namespace.
First Add a reference of System.Configuration to your page.
using System.Configuration;
Then According to your app.config get the connection string as follow.
string conStr = ConfigurationManager.ConnectionStrings["Test"].ToString();
That's it now you have your connection string in your hand and you can use it.
//Get Connection from web.config file
public static OdbcConnection getConnection()
{
OdbcConnection con = new OdbcConnection();
con.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["con"].ConnectionString;
return con;
}
Try this out
string abc = ConfigurationManager.ConnectionStrings["CharityManagement"].ConnectionString;
This worked for me:
string connection = System.Configuration.ConfigurationManager.ConnectionStrings["Test"].ConnectionString;
Outputs:
Data Source=.;Initial Catalog=OmidPayamak;IntegratedSecurity=True"
It is possible that the OP in this question is trying to use an App.Config within a dll.
In this case, the code is actually trying to access the App.Config of the executable and not the dll. Since the name is not found, you get a Null returned, hence the exception shown.
The following post may be helpful:
ConnectionString from app.config of a DLL is null
1) Create a new form and add this:
Imports System.Configuration
Imports Operaciones.My.MySettings
Public NotInheritable Class frmconexion
Private Shared _cnx As String
Public Shared Property ConexionMySQL() As String
Get
Return My.MySettings.Default.conexionbd
End Get
Private Set(ByVal value As String)
_cnx = value
End Set
End Property
End Class
then when you want to use the connection do this in ur form:
Private Sub frmInsert_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim cn As New MySqlConnection(frmconexion.ConexionMySQL)
cn.open()
and thats it. You will be connected to the DB and can do stuff.
This is for vb.net but the logic is the same.
Have you tried:
var connection = new ConnectionFactory().GetConnection(
ConfigurationManager.ConnectionStrings["Test"]
.ConnectionString, DataBaseProvider);
I had the same Issue. my solution was built up from two projects. A Class library and a website referencing to the class library project. the problem was that i was trying to access the App.config in my Class library project but the system was searching in Web.config of the website. I put the connection string inside Web.config and ... problem solved!
The main reason was that despite ConfigurationManager was used in another assembly it was searching inside the runnig project .
The answers above didn't elaborate where the value in connectionStrings index comes from.
As mentioned above, to get your connection string, you say:
string conStr = ConfigurationManager.ConnectionStrings["XXX"].ToString();
To use the correct value of XXX, go to your main projects web.config file and look for the following piece of code:
<connectionStrings>
<add name="Authentication" connectionString="Data Source=(LocalDb)\MSSQLLocalDB;Initial Catalog=Authentication;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\Authentication.mdf" providerName="System.Data.SqlClient" />
</connectionStrings>
Where it says name= , the text within those proceeding quotes is the value of XXX you use in the code above. In my example above, it happens to be Authentication
string sTemp = System.Configuration.ConfigurationManager.ConnectionStrings["myDB In app.config"].ConnectionString;
It seems like problem is not with reference, you are getting connectionstring as null so please make sure you have added the value to the config file your running project meaning the main program/library that gets started/executed first.
First you have to add System.Configuration reference to your project and then use below code to get connection string.
_connectionString = ConfigurationManager.ConnectionStrings["MYSQLConnection"].ConnectionString.ToString();
You can use this method to get connection string
using System;
using System.Configuration;
private string GetConnectionString()
{
return ConfigurationManager.ConnectionStrings["MyContext"].ConnectionString;
}
You can fetch the connection string by using below line of code -
using System; using System.Configuration;
var connectionString=ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;
Here is a reference :
Connection String from App.config
I referenced System.Configuration library and I have the same error.
The debug files had not their app.config, create manually this file.
The error is, I solved this copying the file "appname.exe.config" in debug folder. The IDE was not create the file.
I solved the problem by using the index to read the string and checking one by one. Reading using the name still gives the same error.
I have the problem when I develop a C# window application, I did not have the problem in my asp.net application. There must be something in the setting which is not right.
In order to read the connection string from app.cfg (in windows service application) the below code worked for me
var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
var connectionStringsSection = (ConnectionStringsSection)config.GetSection("connectionStrings");
connectionStringsSection.ConnectionStrings["CONNECTIONSTR"].ConnectionString = #"New Connection String";
Encountered this issue while placing ConfigurationManager.ConnectionStrings in UserControl's constructor, and none of the solution here worked for me.
After some research, seems like ConfigurationManager.ConnectionStrings would be null while trying to access it from the DesignTime.
And from this post, I came up with this following code to detect DesignTime as a workaround to the issue:
public class MyUserControl : UserControl
{
....
public MyUserControl ()
{
InitializeComponent();
bool designMode = (LicenseManager.UsageMode == LicenseUsageMode.Designtime);
if (!designMode)
{
this.connectionString =
ConfigurationManager.ConnectionStrings["xxx"].ConnectionString;
}
}
}

Upload an image during the execution of the code-first migration

OK... so here is something I do not even know if it is even possible. Is it possible to upload an image file during the initial phase of a code first migration? For instance, when creating an initial site user or an admin user that has a portrait image, would it be possible to upload that image during the initial creation of that user?
I couldn't find anything relevant in SO or online that would even come close to even suggest a viable solution so this might be the very first time something like this has even been attempted.
First, create the new migration file (or use the existing one).
Inside Up() method you can put code for
file upload, and inside Down() method code for file removal from
repo (in case you want to revert migration).
Below is one of the many possible ways to do some remote upload, this is one of the simplest:
using (var webClient = new WebClient())
{
webClient.UploadFile("ftp://localhost/samplefile.jpg", "samplefile.jpg");
}
For this to work you should add using System.Net; to the migration file. Also, obviously you need to handle upload permissions and credentials, depending on the type of remote repo you are using.
EDIT:
Using File object is even more trivial. Here is the complete code for migration class:
using System;
using System.Data.Entity.Migrations;
using System.IO;
public partial class MigrationWithFileCopy : DbMigration
{
public override void Up()
{
File.Copy("sourceFile.jpg", "destinationFile.jpg");
}
public override void Down()
{
File.Delete("destinationFile.jpg");
}
}

Possible reasons why SqlConnection is NULL

Using Visual Studio 2012 which was recently installed but now I can't connect to our SQL Server database.
These are the steps I'm following
create App1.config
type this in App1.config:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
<add name ="xxx" connectionString="USER ID=xx;PASSWORD=xx;PERSIST SECURITY INFO=True;Data Source=xx;Initial Catalog=xx" />
</connectionStrings>
</configuration>
Add a reference to the project to System.Configuration
Create access to namespaces via:
using System.Data.SqlClient;
using System.Data;
using System.Configuration;
implement the following:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;
namespace ConsoleApplication10 {
class Program {
static void Main(string[] args) {
SqlConnection conn = null;
conn = new SqlConnection(ConfigurationManager.ConnectionStrings["xxx"].ConnectionString);
}
}
}
I've created a new console app and added the above and I still get an error NullReferenceException was unhandled Object reference not set to an instance of an object. ...
EDIT
Via the immediate window I determined that the following is null:
ConfigurationManager.ConnectionStrings["xxx"].ConnectionString
If I hard-code the connection string into the constructor for SqlConnection then it connects ok
What am I missing - something really obvious!! Or is this in connection with my new VS ?
check what is in the ConfigurationManager.ConnectionStrings by excecuting at least the following:
if (ConfigurationManager.ConnectionStrings != null ) {
Console.WriteLine(ConfigurationManager.ConnectionStrings.Count);
Console.WriteLine(ConfigurationManager.ConnectionStrings[0].ConnectionString);
Console.WriteLine(ConfigurationManager.ConnectionStrings[0].Name);
....
} else {
Console.WriteLine("null");
}
This will highlight any obvious problems like duplication of the App.config file which could well be the case as you mentioned App1.config in the OP.
Check your output folder.
Assuming your application is called myapp.exe, there should be myapp.exe.config.
This should exist, and should contain the contents of your app.config file in Visual Studio.
If it doesn't, check whether you already have an app.config file elsewhere (I notice you called your file app1.config)
Have your tried checking what the value of ConfigurationManager.ConnectionStrings["xxx"].ConnectionString is and hardcoding with that value? Do you still get null?
Also it's advised to created the connection like this:
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["xxx"].ConnectionString))
{
//code
}
I would reply but I don't have enough rep yet ... :-(
Guessing from the fact that your code does not "do anything" with conn yet, I'm pretty sure that the ConfigurationManager returns null for the connection string name you pass in. An exception is thrown by the SqlConnection's constructor when passing in null instead of a valid connection string.
When you place your connection strings in Properties->Settings, as a connection string, access them with full namespace, and your done.
See my answer here

How can I run a series of sql scripts with EF 4.3 Migrations?

I am trying to do something like this in the Seed method:
foreach (string sqlFile in Directory.GetFiles(Path.Combine(Directory.GetCurrentDirectory(), #"SqlScripts")))
{
string sqlText = File.OpenText(sqlFile).ReadToEnd();
context.Database.ExecuteSqlCommand(sqlText);
}
When I run Update-Database I get the error:
Could not find a part of the path 'C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE\SqlScripts'.
So clearly update database is running from the VS bin directory and not from the project directory. Without having to resort to hard coding a path to the project (there are multiple developers working on this), how do I go about getting the path of the assembly that contains the DbContext?
I wanted to do something similar, but I always found Seed a little dim given that the point of Migrations is a versioned database, while a Seed command ignores versioning - so it can easily shoot you in the foot. The preferable result is data motion in Migrations instead. So, here we go:
(Full source on GitHub, with a few other Migrations commands.)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Data.Entity;
using System.Data.Entity.Migrations;
using System.IO;
using System.Text.RegularExpressions;
public abstract class ExpandedDbMigration
: System.Data.Entity.Migrations.DbMigration
{
public void SqlFile(string path)
{
var cleanAppDir = new Regex(#"\\bin.+");
var dir = AppDomain.CurrentDomain.BaseDirectory;
dir = cleanAppDir.Replace(dir, "") + #"\";
var sql = File.ReadAllLines(dir + path);
string[] ignore = new string[]
{
"GO", // Migrations doesn't support GO
"/*", // Migrations might not support comments
"print" // Migrations might not support print
};
foreach (var line in sql)
{
if (ignore.Any(ig => line.StartsWith(ig)))
continue;
Sql(line);
}
}
}
AppDomain... gets you the proper directory for your Models Project, instead of pointing you to Visual Studio as other methods would.
The Regex cleans up what's returned in case it's running from a bin folder.
ReadAllLines reads in your Sql script; in this case it's stored in \Sql\blah.sql but you could put it somewhere else.
The foreach/ignore prevents commands like "GO" from getting in, which will error out when used in Migrations, and are frequently emitted from tools like Sql Server Management Studio Generate Scripts.
Finally the foreach dumps each line out to Migrations.
Usage:
using Brass9.Data.Entity.Migrations;
public partial class FillZips : ExpandedDbMigration
{
public override void Up()
{
SqlFile(#"Migrations\Sql\2013-08-15 FillTable.sql");
}
Notice the change in inheritance, from DbMigration to ExpandedDbMigration.
Replace the argument to SqlFile with whatever the path is to the sql file inside your Migrations-enabled project.

The EntityContainer name must be unique. An EntityContainer with the name 'Entities' is already defined

For a little background:
I have a DLL project with the following structure:
Rivworks.Model (project)
\Negotiation (folder)
Model.edmx (model from DB #1)
\NegotiationAutos (folder)
Model.edmx (model from DB #2)
I have moved the connection strings from this project's app.config to the web.config file. They are not in the ConnectionString section. Rather, I have a static class that consumes part of the web.config and exposes them to my app as AppSettings.[settingName].
<FeedAutosEntities_connString>metadata=res://*/;provider=System.Data.SqlClient;provider connection string='Data Source=db4;Initial Catalog=RivFeeds;Persist Security Info=True;User ID=****;Password="****";MultipleActiveResultSets=True'</FeedAutosEntities_connString>
<RivWorkEntities_connString>metadata=res://*/NegotiationAutos.NegotiationAutos.csdl|res://*/NegotiationAutos.NegotiationAutos.ssdl|res://*/NegotiationAutos.NegotiationAutos.msl;provider=System.Data.SqlClient;provider connection string='Data Source=db2;Initial Catalog=RivFramework_Dev;Persist Security Info=True;User ID=****;Password="****";MultipleActiveResultSets=True'</RivWorkEntities_connString>
I have 2 classes, one for each Context and they look like this:
namespace RivWorks.Model
{
public class RivWorksStore
{
private RivWorks.Model.Negotiation.Entities _dbNegotiation;
public RivWorksStore(string connectionString, string metadata, string provider)
{
EntityConnectionStringBuilder entityBuilder = new EntityConnectionStringBuilder();
entityBuilder.ConnectionString = connectionString;
entityBuilder.Metadata = "res://*/"; // metadata;
//entityBuilder.Provider = provider;
_dbNegotiation = new RivWorks.Model.Negotiation.Entities(entityBuilder.ConnectionString);
}
public RivWorks.Model.Negotiation.Entities NegotiationEntities()
{
return _dbNegotiation;
}
}
}
namespace RivWorks.Model
{
public class FeedStoreReadOnly
{
private RivWorks.Model.NegotiationAutos.Entities _dbFeed;
public FeedStoreReadOnly(string connectionString, string metadata, string provider)
{
EntityConnectionStringBuilder entityBuilder = new EntityConnectionStringBuilder();
entityBuilder.ConnectionString = connectionString;
entityBuilder.Metadata = "res://*/"; // metadata;
//entityBuilder.Provider = provider;
_dbFeed = new RivWorks.Model.NegotiationAutos.Entities(entityBuilder.ConnectionString);
}
public RivWorks.Model.NegotiationAutos.Entities ReadOnlyEntities()
{
return _dbFeed;
}
}
}
You will note that the MetaData is being rewritten to a short version.
When I comment out that line in each class I get this error:
Unable to load the specified metadata resource.
When I leave that line in in each class I get this error:
Schema specified is not valid. Errors:
Negotiation.Model.csdl(3,4) : error 0019: The EntityContainer name must be unique. An EntityContainer with the name 'Entities' is already defined.
I know it is something simple, something obvious. Any suggestions welcome...
Hijacking this, since it is the top Google result for the error message.
In case anyone else encounters this while only using a single model/context: I once ran into this problem because the assembly containing the model/context was renamed and a copy with the previous name remained in the bin directory of the application. The solution was to delete the old assembly file.
Your two EDMX files probably have the same entity container name. You need to change (at least) one of them.
In the GUI designer, open Model Browser. Look for a node that says "EntityContainer: Entities". Click it. In Properties, change Name to something else. Save and rebuild.
I had the problem too but my solution was to clean the bin directory and then remove the connection string with the entity container name. Then I could rename my entities and put back the connection string.
I renamed my project but the old file was still in the bin folder. I just had to delete the old DLL from the bin folder.
I have found a way to save multiple containers with the same name (namespaced of course).
In EF5 and VS2012 you can set three different namespaces. First you can click on the edmx file in the solution browser and in the properties windows you can set the "Custom Tool Namespace", you can click on the *.Context.tt file right below the edmx and set another namespace there, and finally thanks to a lead from Mr Stuntz awesome answer I realized that by opening the edmx file and clicking in the white space you get another namespace field under Schema in the properties window.
Think we're done, not quite, I know you can see the Entity Container Name field and will try to change the name there but that doesn't seem to work, you get a little error that pops up. Ensure that all your edmx files have an individual namespace there. (I ensured I had a unique namespace in all three places)
Then go to your Model Browser and right click on EntityContainer: Entity to go to properties and change the name of your container(s). From that window with the namespace set everywhere I was able to get multiple contexts with the same name. I was dealing with things like blahcontext and blahcontextcontainer all of a sudden even though they were in different folders.
When you see that its a namespace problem. Or lack thereof.
In my case, the problem was caused by my connection string in Web.config being named the same thing as my entities container class.
Change
<add name="ConflictingNameEntities" connectionString="metadata=res://*/blahblah
to
<add name="ConflictingNameEntitiesConnection" connectionString="metadata=res://*/blahblah
and regenerate the container class by right-clicking ConflictingNameModel.Context.tt in Solution Explorer and clicking "Run Custom Tool".
I just ran into this. It looks like somehow Entity Framework got into a bad state in terms of what tables it thought it needed to add.
Normally EF will not recognize that a new table has to be created until you put the line
public virtual DbSet<NewTable> NewTable { get; set; }
inside your context class.
However, EF somehow got into a bad state where the mere presence of the NewTable class in my solution was triggering it to think that it needed to generate that table. So by the time the above line in the context triggered it to create a NewTable table, it already thought it had done it, hence the error about duplicate entities.
I just removed the NewTable class from my solution, commented things out so it would compile again (thankfully there wasn't too much of this), then added a new migration to make sure it was blank as it should have been. Then once things were back into a more predictable state, I re-added the NewTable class back into the solution and adding the migration worked fine.
If you are using web deployment from Visual Studio sometimes doesn't delete the old dlls. I had the same problem, change to Web Deployment Package and didn't give me problems.
I had a same problem in my asp.net website, to resolve the problem I purposely added compile time error in one of the cs file in the app code by removing a semicolon, then I rectified the compilation problem by adding semicolon again.
This process caused application to compile again.After this error got vanished.
The other cause of this problem, your add model in any solution project and change your model project.
--PROJECT A --> MODEL.EDMX
--- WEB CONFIG -->Entity Connection
--PROJECT B
--- WEB CONFIG -->Entity Connection
Later, I think this structure is bad and Change project.
--PROJECT A
using PROJECT.C;
WEB.CONFIG - USE PROJECT C APP.CONFIG CONNECTIONSTRING
--PROJECT B
using PROJECT.C;
WEB.CONFIG - USE PROJECT C APP.CONFIG CONNECTIONSTRING
--PROJECT C (CLASS LIBRARY) --> MODEL.EDMX
--- APP.CONFIG -->Entity Connection
Everything was fine but I get an error.
Error Detail : The EntityContainer name must be unique. An EntityContainer with the name 'Entities' is already defined
Because I forgot change Web.Config files.
OLD WEB.CONFIG
<add name="donatelloEntities" connectionString="metadata=res://*;provider=System.Data.SqlClient;provider connection string="data source=.;initial catalog=donatello;persist security info=True;user id=1;password=1;multipleactiveresultsets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
NEW WEB.CONFIG
<add name="donatelloEntities" connectionString="metadata=res://*/EntityModel.Model.csdl|res://*/EntityModel.Model.ssdl|res://*/EntityModel.Model.msl;provider=System.Data.SqlClient;provider connection string="data source=.;initial catalog=donatello;user id=sa;multipleactiveresultsets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
This Problem is Simple but may cause loss of time. I wanted to give an example. I hope is useful.
Thanks.
To solve the issue Entity 6.2.0, VS 2017, single edmx
I changed the name of my model.edmx to another name, built the project, then changed it back to the original name.
In my case, probably after merging a version back, my startup project file (csproj) got corrupted.
Al the Entity classes where added:
<Compile Include="Class.cs">
<DependentUpon>MyModel.tt</DependentUpon>
</Compile>
After removing all relevant entries by hand the problem was solved.
Strange problems have strange answers, so please do not blame.
first, take a quick look at this part of code
I got a problem the problem
The EntityContainer name must be unique. An EntityContainer with the name 'Entities' is already defined
with this class name 'ShippingSpeed_Month_Speed'
The solution for me was just renaming 'speeds' to 'speedsx'.
So, you MAY need to rename something like the ending name of the relation or navigational property which is the same ending of the same table name or the ending name of the DbSet<>
I'm answering to document what worked for me and hoping to benefit others.
Thanks
No bin, just aspx/edmx ? Just move the shema files (mode.edmx + model.designer.vb) refresh and put them back ! IIS/aspnet probably corrupt for x reason.

Categories