Database and database schema suddenly out of sync - c#

I have (I think) a very strange problem.
I have a web server running an ASP.NET MVC app querying a SQL Server database. It has all been constructed using code-first approach.
It has been working without problems for a long time, and whenever I have needed e.g. a new column in a table, I have added the needed class to the model in question. Then I have run Add-migration 'Migration_Name', and a script has been generating with the proposed changes, and after running update-database, the changes have been applied to the database. Easy and always working.
Yesterday, without making any changes to the database or the models (and by the way not even updating the web-server) it stopped working.
The database throws an error the moment the web-app tries to access the database
System.Data.SqlClient.SqlException: 'CREATE TABLE permission denied in database 'master'
The content of the database is intact I can see from browsing it from within Visual Studio.
If I run the add-migration command, a script is generated for every single table, column, foreign key etc for the entire database, as if the database did not contain a single one of the classes defined in the models.
So it seems that the database is not in sync with my code first models anymore. I got my IT department to copy the entire database to a test server to try to test what is wrong without messing up the production database, and after trying to run the "strange" migration script by using the update-database command, I get the same error:
CREATE TABLE permission denied in database 'master'
and it shows me that it fails when trying to create the first table in the migration script. This is not surprising, since it already exists in the database. But what is going on - I am at a loss!
So can anyone tell me might have happened here, and more importantly, how to fix it?
All the best
Troels

Related

How do I add columns to database without users losing data when a new version of the application is published?

I have a c# .NET application with a SQLLocalDB database. I have used database first to create the EF6 model. I have added columns to one of the tables using SQL Server Management Studio and then used 'Update model from database' to propagate the changes into my model. When doing this, data on the development PC is unaffected and incorporates the new columns. However, when a different user runs the new version of the application, their existing datafile (.mdf) won't recognise the new columns and crashes with the exception:
System.Data.Entity.Core.EntityCommandExecutionException: An error occurred while executing the command definition. See the inner exception for details. ---> System.Data.SqlClient.SqlException: Invalid column name 'VAT_long_description'
making the user's existing data in that table unreachable. I appreciate that Code First gives the ability to migrate data, but this facility appears not to be available when building the EF model using database first.
My connectionString is:
<add name="PMMEntities" connectionString="metadata=res://*/PMMData.csdl|res://*/PMMData.ssdl|res://*/PMMData.msl;provider=System.Data.SqlClient;provider connection string="data source=(localdb)\v11.0; AttachDBFilename=|DataDirectory|\PMM.mdf; initial catalog=PMM;Integrated security=True;MultipleActiveResultSets=True; App=EntityFramework""providerName="System.Data.EntityClient" />
I want to ensure that when a user installs a new version, their .mdf datafile will adapt to the new database schema without loss of data. It seems the only way to do this is through running a conversion or migration method on startup if the app throws the “Invalid column name” SQL exception. Where can I find the code (or a NuGet package) that will do this?
if you are using MVC , you have two methods to make an update in your models class database. the most easy way to resolve that issue is that you delete the model class related to the database and you import it again into your model folder. don't worry about data, they will still stored in your database. unless you have wrotten some extra object in the model class database, in this case you will waste those extra objects.. it will not affect your storage.

C# switch from local db to external (Azure) db causes errors

I have used the built in Database that comes with Visual studio by using Code First with Entity Framework. Now I wanted to move to an external database so I created one and saved the connections string. So I connected to my azure database by supplying the connection string in the db context constructor. Now though, the problem is that Entity Framework isn't able to create the necessary tables. When I run my application and try to access something, I get System.Data.SqlClient.SqlException: 'Either the parameter #objname is ambiguous or the claimed #objtype (COLUMN) is wrong.'
And I assume this is beacuse my azure db is empty. Why doesn't Entity Framework create the tables?
The error was that I had forgotten to run migration on the new database:
*Add-Migration newDb
*Update-Database

AutomaticDataLossException thrown after initial migration runs in EF 6 in SQL Server but not MySQL

Background info:
I am about to start a new project written in C# (vs2015) which will be using Entity Framework 6 within its DAL. One of the core requirements is that the system must be able to run against either SQL Server, Azure SQL server, MySQL or Oracle as chosen by the user simply changing the connection string in the web.config.
So prior to the project kick-off I am trying to get more familiar with Entity Framework as I have not used it outside of a few tutorials before.
I have written a small proof of concept app, the purpose of which is to determine how I can use EF to quickly swap a web api to use a different underlying DB. For the PoC I am using SQL Server express v12 and MySQL v5.6, C#, Entity Framework 6 via a code first approach.
I have hit a road block with my PoC, I am seeing different behaviour when running against MySQL compared to when I am running against SQL Server. I am using the following EF context:
<context type="POC.Core.Api.DataAccessLayer.SchoolContext, POC.Core.Api" disableDatabaseInitialization="false">
<databaseInitializer type="System.Data.Entity.MigrateDatabaseToLatestVersion`2[[POC.Core.Api.DataAccessLayer.SchoolContext, POC.Core.Api], [POC.Core.Api.Migrations.Configuration, POC.Core.Api]], EntityFramework"></databaseInitializer>
</context>
I have two migration scripts, one which is the initial creation and another which just adds a property to an object.
I have some test data being created in the seed method in the configuration class which looks like this (:
public Configuration()
{
AutomaticMigrationsEnabled = true;
this.SetSqlGenerator("MySql.Data.MySqlClient", new MySql.Data.Entity.MySqlMigrationSqlGenerator());
}
protected override void Seed(WeldOffice.Core.Api.DataAccessLayer.SchoolContext context)
{
var students = new List<Student>
{
new Student { FirstMidName = "Carson", LastName = "Alexander",
EnrollmentDate = DateTime.Parse("2010-09-01") },
...
};
Both my MySQL and SQL servers do not yet have the database present at all yet.
As I want the user to be able to specify the DB I am relying on in-code methods to create the DB structure etc.
Given this scenario, my understanding is that the following occurs when the db context is first hit when running the app:
Check for existence of the database - it is not present so it will be created.
Check if the initial creation script has been run - it has not so run it.
Check if the add property script has been run - it has not so run it.
Run the seed method to ensure data is present and correct.
In MySQL this all works as expected, the database is created, the tables set up and the data populated. The two migration scripts are listed in the migration table.
In SQL Server, steps 1,2,3 all work and the database is created and the tables set up. The two migration scripts are listed in the migration table. However, step 4 is not run, the Seed method is never hit and instead a AutomaticDataLossException exception is thrown.
If I set AutomaticMigrationDataLossAllowed = true then step 4 also works and everything is as expected. But, I would not really want to have AutomaticMigrationDataLossAllowed set to true and don't see why this is necessary in SQL server but not MySQL. Why is this the case? I feel I am missing something fundamental.
Please keep in mind this is just a proof on concept, in production there will be no seed data anyway, and I would rather a dba create the db via sql scripts etc.

Why is entity framework giving this error on web server?

I'm trying to use Entity Framework to add records to a database from a webform input that go into a database on sqlserver.
Everything works fine locally.
I used webmatrix to publish my site to my remote server, the website and my local version of the database is successfully recreated on the remote server with all the data.
However when it comes time to add records to the database, it gives an error on the remote server which i managed to trace to the ctx.Students.Add line.
using (var ctx = new HDPS_SchoolDataEntities())
{
SchoolDataModel.Student temp = new SchoolDataModel.Student();
temp.Name = this.FirstName;
temp.Surname = this.Surname;
temp.Parents = this.Parents;
ctx.Students.Add(temp);
ctx.SaveChanges();
}
I can't find any difference between my local version that works and the one on the remote server that doesn't work. The web.config seems to be configured as expected and all the necessary dll's are in my bin folder but it just won't work on the remote server... any ideas what could be wrong?
Oops forgot the error message!
edit
after Installing .net 4.5 and changing the connection mode from windows authentication to SQL authentication the error now becomes:
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.
Everything should be the same on the webserver as the entire website is being copied across but it works fine locally so not sure what the problem is...
OKay I solved the issue with the help of this webpage
http://blog.oneunicorn.com/2012/02/26/dont-use-code-first-by-mistake/
In short It seems webmatrix was does not include the metadata part of the connection string on upload to the server thus the EDMX file containing all the information mapping the classes to the database tables was not being referenced causing any queries to the framework to fail.
Once i pasted the original connection string generated by the Entity Framework wizard onto the server everything worked fine.
Based on the error given in your comment, it sounds like you are failing to connect to the database. Check your connection string, username and password. If those are correct, make sure your database settings allows connections from your server ip address.
OKay I solved the issue with the help of this webpage
http://blog.oneunicorn.com/2012/02/26/dont-use-code-first-by-mistake/
It seems webmatrix was does not include the metadata part of the connection string on upload to the server thus the EDMX file containing all the information mapping the classes to the database tables was not being referenced causing any queries to the framework to fail.
Once i pasted the original connection string generated by the Entity Framework wizard onto the server everything worked fine.

Connection string hidden somewhere?

I have two databases on one machine that also has two different sites running on IIS. Lets call them Site1 & Site2 and DB1 & DB2. The second site and BD are copys of the first one. The Site2 connects to DB2 and everything seems to work nice but when we took offline the DB1 it stoped working which is wierd since all the data created using the site2 was in DB2. In fact most of the site works except for one method
We use entity framework to access the database and when we trace the code everything looks ok, but it somehow doesn't work.
In our auto-generated code by entity framework we traced the connectiong string and the outcome is correct
Initial Catalog=DB2;
But in the next line we have this code
return ((IObjectContextAdapter) this).ObjectContext.ExecuteFunction<T_REFERENCE_DATA>(
"GetReferenceData", groupNameParameter);
And we get an inner exception that says:
Database 'DB1' cannot be opened because it is offline.
All the other methods seem to use the correct database except this one. We can't figure out where the DB1 is configured or hardcoded
The problem was (as usual) stupid as hell. Some of the guys defined the DB on the stored procedures. When we changed DB and copied the stored procedures they kept using the old DB. It is now fixed.
Thanks for your help

Categories

Resources