I have an ASP.NET MVC project that was completed on one system and saved to GitHub. Now I have downloaded the projected as a ZIP file from Github and I am trying to execute it. As there is no local database on my system, how should I create the database again without starting up with a new project and copying the code?
I do not want to create the SQL table manually when it can be scaffolded using MVC. AFAIK, when there is no existing database with the name of the database, the database is created and the tables are created. But no table or database is created.
It throws the following exception
An underlying operation failed an Open
Update
I could remove the above exception to get a new exception
The context cannot be used while the model is being created. This
exception may be thrown if the context is used inside the
OnModelCreating method or if the same context instance is accessed by
multiple threads concurrently. Note that instance members of DbContext
and related classes are not guaranteed to be thread safe.
More info on the Project
The project is using Windows Authentication. And the calls to every page in the project is validated before the page is viewed. As I have no table called Users in the database, I get an exception The underlying operation failed an Open. I tried to call the Create User method, and create a user with my current credentials, but I am unable to save changes to the database.
First in web.config find connection string and change Data Source
value to your SqlServer address, we assume you use SSMS in your
windows,
some thing like this:
<connectionStrings>
<add name="ApplicationConnectionString" connectionString="Data Source=.;Initial Catalog=DB;Persist Security Info=True;" providerName="System.Data.SqlClient" />
</connectionStrings>
Socond open package manager console from View and then write
Add-Migration InitialCreate
after executing this command, write
update-database
Related
I have a Windows Azure Mobile Services app that has a Code First generated database. The connection string (for when run locally) looks like this:
<add name="MS_TableConnectionString" connectionString="Data Source=(localdb)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\<database_name.mdf;Initial Catalog=<database_name>;Integrated Security=True;MultipleActiveResultSets=True"
providerName="System.Data.SqlClient" />
I created a new Console App project, referencing the Mobile Services project, and copied this connection string to the App.config file
In Program.Main() I created a new instance of the Context class from the Designer in the Mobile Services project. But when I run the Console App, and try to access one of the DbSets made public by the Context, I get the following exception:
"An exception occurred while initializing the database. See the InnerException for details."
With an inner exception of:
"The underlying provider failed on Open."
Which in turn has an inner exception of:
"Cannot attach the file 'C:\\...\\<database_name>.mdf' as database '<database_name>'."
If I remove the AttachDbFilename part of the connection string in the Console App, I get the following exception at the same point in the code:
"Cannot create more than one clustered index on table 'dbo.<Table_Name>'. Drop the existing clustered index 'PK_dbo.<Table_Name>' before creating another"
Does anyone have any idea why it would be trying to create this new clustered index when there already appears to be one?
Or any ideas what connection string I should use just to get a normal read/write connection to the database without it doing anything weird? Is this related to database initialization?
Edit: I've had a bit more of a play around with this, this morning. I can get it working without exceptions if I remove the inheritance of "Microsoft.WindowsAzure.Mobile.Service.EntityData" from my model classes, so this appears to be pretty significant.
Ok I've just battled through this and got it working. Gonna type this up in case it helps anyone one day.
So the problem is something to do with the fact that my Code First model classes were inheriting from EntityData. As I said in my edit above, removing this inheritance does appear to fix the problem. I think this is because the EntityData class has both a property with a [Key] attribute and a separate property with a [Index(IsClustered = true)] attribute. Because you can't have more than one Clustered Index in a table, the database initialization fails. In the default Azure Mobile Services project, there must be some magic that means this doesn't happen somewhere - but from a separate project you get the "Cannot create more than one clustered index on table" exception.
So what I did was disable Database Initialization in the separate Console App by adding the line:
Database.SetInitializer<MobileServiceContext>(null);
...before the DbContext is instantiated.
This allows me to use the database initialized by the Mobile Services App as an existing database, without attempting to make any changes to it.
I also needed the following AppSetting in the config file of the Console App, in order for it to use the correct Schema Name:
<add key="MS_MobileServiceName" value="<CorrectSchemaName>" />
I'm getting the above error when using EF code first. Everything works as expected when running my code for the first time, but when I delete my database and run the code again the exception is thrown. It seems like EF is not creating the database the second time around and seems to thinks the database still exists.
When I reset iis, EF is able to create the database again (Only the first time).
Here is my connection string
<add name="DatabaseContext" connectionString="Data Source=MyServer;Initial Catalog=UnitTest;Persist Security Info=True;User ID=MyUser;Password=MyPassword" providerName="System.Data.SqlClient" />
When running the application, the first query execution will build a metadata model per application domain and each new DbContext will reuse the global metadata.
I'm afraid when you drop the database, the same application domain is still being used to execute the query, but EF still thinks that the database has been created because the metadata is cache globally. This kind of behavior is rarely happened.
But you can try to execute the database explicitly if it doesn't exist. This will create additional overhead to check the database existence every query execution.
using (var db = new AppContext())
{
if (!db.Database.Exists())
{
db.Database.Initialize(true);
}
// query
}
Or you can put it in the constructor.
I have a made an EntityFramework model based on my Demo Database.
I want to include connection strings for Staging and production and then in my Console App prompt the user to see which database they want to perform the operation on.
When I was prompted to setup the EF.edmx file I just chose to store the connection string in the app.config file. I have seen a link to change the Connection string of EntityFramework Context when initializing it here
However when I store another connection to my Staging Database, I get an error "Keyword not supported: 'metadata'"
So I stripped down the connection string not to include the EntityFramework type of parameters such as metadata=res://*/MyDBItems.csdl|res://*/MyDBItems.ssdl blah blah
and used a very simple database connection string
data source=myDB;initial catalog=myDB;user id=myUser;password=myPass;MultipleActiveResultSets=True;
now my Context does instanciate but when I get to a query I get another error about:
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.
How can I switch between different databases with Entity Framework 5, thanks!
forget it I got it....what I did...I made a 2nd constructor in the Context.cs file
public MyContext(string dbModel) : base("name="+dbModel) {
}
then in my app.config I have the various settings for the Demo,Staging & Production database connections....this took the full entityframework connection string. I think the link I provided was for Code-First but I am using Database First.
I seem to be having a problem with Entity Framework code-first. I managed to make it create the database in my project folder in App_data and everything works well if I do not try to check the contents of the generated database in the Server Explorer.
If I do that and try to open the application I get this error:
Cannot open database "SellCars" requested by the login. The login failed.
Login failed for user 'Aly-PC\Aly'.
While this behavior may be normal (not really sure), even if I detach the db and close the connection in the server explorer and I run this application it still does not work but instead in throws this error:
One or more files do not match the primary file of the database. If you are attempting to attach a database, retry the operation with the correct files. If this is an existing database, the file may be corrupted and should be restored from a backup.
Cannot open database "SellCars" requested by the login. The login failed.
Login failed for user 'Aly-PC\Aly'.
Log file 'D:\Projects IDE\Visual Studio\MyWork\Websites\SellCars\SellCars\App_Data\SellCars.ldf' does not match the primary file. It may be from a different database or the log may have been rebuilt previously
This is my connection string:
<add name="CarsEntities"
connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename='D:\Projects IDE\Visual Studio\MyWork\Websites\SellCars\SellCars\App_Data\SellCars.mdf';Initial Catalog=SellCars;Integrated Security=True;User Instance=True"
providerName="System.Data.SqlClient" />
I do not try to change anything inside of the database not even add any data but I still get these errors.
What should I do?
Add Aly-PC\Aly to the active directory users who can access the SQL server. Then add the SQL server login you just created to the database.
I deployed C# application and created installer. Installer gets created successfully but when tried to launch the application it throws up following error:
An attempt to attach an auto-named database for file CampusPointe.mdf
failed. A database with the same name exists, or specified file cannot
be opened, or it is located on UNC share.
connection string in app.config is as follows:
<connectionStrings>
<add name="App_Key_Management.Properties.Settings.VendorKeyConnectionString1"
connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename="C:\Program Files\Vendor Key Management\VendorKey.mdf";Integrated Security=True;Connect Timeout=30;User Instance=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
Any help would be appreciated.
Regards,
Sri
Sri,
First of all, you need to ensure a couple of things:
1. You have installed SQL Server
2. You need to deal with the creation or replacement of the file you created. I think this is your issue ... If the .mdf file exists then you need to either update the existing file or drop and replace it (USE [database] GO DROP TABLE... GO CRATE TABLE ... GO). You will also need to consider step 4 below.
3. If you are accessing a a file located in a database you need a fully formed name. You also need to add the database user to the connection string in ASP.NET Web.Config or App.config (depending on the app). I looks like you have started this ...
4. Make sure the user account that you are using in the connection string has the necessary privileges on the database side. If this is a full fledged database in SQL SERVER then the user account will need update, delete, create privileges. If you are replacing or creating databases on the fly then the user will need CREATE DATABASE or DROP / CREATE privileges.
I think to best answer your question we would need more information on the architecture of the application. My guess is that your code creates the database fine the first time and then when you try to run it the second time it fails because the database is already there. If this is the case you also need to address your code (with IF statements or SWITCH CASE ... your call) to handle situations where the table (1) does not exist and needs to be created; (2) exists and needs to be updated; and / or (3) exists and needs to be replaced. The correct answer again depends on your code and what you are trying to do.