Am trying to learn ASP.NET MVC and search the internet in and out including SO. A lot of questions and answers about |DataDirectory| as where and how.
When debugging the site breaks:
"The model backing the 'ASPNETDBContext' context has changed since the database was created...".
Then I checked the path: |DataDirectory|ASPNETDBContext.sdf
string path = AppDomain.CurrentDomain.GetData( "DataDirectory" ).ToString();
It points to the App_Data of the project but no file there.
The DB is entirely empty so deleting the thing is all I need.
My actual question I need to be answered: How to fix this properly?
made a follow-up: And additionally: Where is that file!
The answer to your problem lies in reading Scott Guthrie's blog
For those who are seeing this exception:
"The model backing the 'Production' context has changed since the database was created. Either manually delete/update the database, or call Database.SetInitializer with an IDatabaseInitializer instance."
Here is what is going on and what to do about it:
When a model is first created, we run a DatabaseInitializer to do things like create the database if it's not there or add seed data. The default DatabaseInitializer tries to compare the database schema needed to use the model with a hash of the schema stored in an EdmMetadata table that is created with a database (when Code First is the one creating the database). Existing databases won’t have the EdmMetadata table and so won’t have the hash…and the implementation today will throw if that table is missing. We'll work on changing this behavior before we ship the fial version since it is the default. Until then, existing databases do not generally need any database initializer so it can be turned off for your context type by calling:
Database.SetInitializer<Production>(null);
Hope this will help you resolve the issue.
Related
The EF7 migration add command (to date, beta5) compares the model classes defined in the DbContext against the current model snapshot, creates a new migration class, and updates the model snapshot.
I need to modify the migration to make it generate different DDL SQL. As an example, EF7 uses sequences for SQL Server auto-increment values, and I would like it to use identity. However it could be any other reason. The migration remove command would physically delete the migration files and revert the model snapshot, so it's useless in this case.
There are 3 files that contain related code that look like they need to be edited:
The primary migration class: The Up and Down methods should be modified.
The DbContextModelSnapshot file contains Annotations that need to be modified
The secondary migration partial class: The badly named [migration].Designer.cs file also contains a model snapshot for the migration. I'm assuming this snapshot needs to match the model snapshot in item 2, but am not certain. The only information I have about the purpose of it is from Brice's blog , which says "It’s there in case you or a provider need to inspect the model for additional information during a migration."
Specific questions:
Do the two model snapshots need to be kept in sync in order to correctly perform migrations?
Is modifying 3 separate files the only way to edit the migration? (Although depending on the changes, the model snapshots may not have to be touched in some cases.)
Is there some EF command that would regenerate just the model snapshots, but not the migration methods?
Specific answers:
Do the two model snapshots need to be kept in sync in order to correctly perform migrations?
No, the snapshot in the migration is a last resort for provider writers. For example, SQLite can't rename columns so it could use migration's model snapshot to do a table rebuild for this operation. 99% of the time, it won't ever be used.
Is modifying 3 separate files the only way to edit the migration?
Most of the time, you should only ever edit the main migration file. In rare cases, you may need to edit the model snapshot if you're working in a team environment and you encounter a merge conflict. You can ignore the designer file; it just captures some metadata about the migration.
You may not have to edit anything if you configure your model correctly. For example, to use identity instead of sequences, override DbContext.OnModelCreating() and add modelBuilder.ForSqlServer().UseIdentity().
Is there some EF command that would regenerate just the model snapshots, but not the migration methods?
No, it shouldn't be needed since you almost never edit these files.
So my problem is, I added a extra column in My one of the table in database in SQL and i wanted to reflec that change in my MVC project. So what i usually do is update the model from the database and it works all the time.But this time it didnt worked so i thought let me delete the table from Project1Model.Store>Tables/Views from the EDMX Model Browser and then update the model from Database(which worked in past for me). But by mistake deleting the SessionDetail table i deleted the sysdiagram table from tables/Views.
Now i dont have sysdiagram table in my Tables/Views section but i can see that table in diagram and in EntityTypes. I tried generating model from databse but didnt worked. I dont want to create Database from Model because i know i deleted something from my model and dont want to effect my database which is fine(let me know if i am wrong this the right way).
I still get this error after built the solutions. Let me know how i can recreate the sysdiagram table in my Table/Views section.
Thanks in Advance.
-Arpan
I had the same error and went to the .edmx and deleted the sysdiagram table and everything worked well.
I initially had been connected to a database that had a database diagram but later I connected to a copy of that database but without a diagram which I guess was the source of the problems.
So to conclude first check if you have a diagram in the db, if not either recreate it and update your model from db, alternatively completely delete sysdiagrm table from your model.
Yesterday i was absolutely sertain that all migrations data for EF placed in classes, placed in my solution as nested from DbMigration. But today i was dig a slightly deeper(just try to fallback to old migration with enable data loss not with nu-get and visual studio, but with code())
DbMigrator fg = new DbMigrator(new Settings() { AutomaticDataLossEnabled = true});
fg.Update("MigrationName");
And get exception, smth like "string should be truncated", those means that migrator tried to update column from big to small MaxLength attribute. So, i had excluded migration that caused this update and move this changes to migration, those create tables. The error still was occured. I got to intellitrace and it said that those(deleted) migration still was called. Looking to requests told me things like this:
SELECT [Extent1].[MigrationId] AS [MigrationId] FROM [dbo].[__MigrationHistory] AS [Extent1]
Looking to a table __MigrationsHistory and get my deleted migration there with field model that contains crypted data(don't decrypt this yet) . I was realy shocked. Does this means that all code, have written in classes is just the fake and really executed code placed here? And does anyone know, how to work with this table, register projections of migration classes to it etc. Or the once way to work with migrations is nu-get console?
I am not fully sure what your primary question is, so I will first try to answer last part about __MigrationHistory table.
Code in classes is not fake, your code in classes is compiled and run.
This table, however, really contains your database model, but it is not encrypted, it is compressed. The reason why Migrations API needs to store your model, is to be able to compare it against your current actual model and track changes for you (for example when you add a new property it will be able to tell what property you added and to perform automatic db migration).
In previous version of EF there was an EdmMetadata table where hash of your model was stored, and EF was able to detect if you made some changes to model by comparing stored and current model hash value. New version when migrations are enabled stores entire model as compressed blob, so it can do diff between the model that was used to create database and current model you are using, and make automatic migrations accordingly.
You should not work directly with this table, it is automatically populated by migrations API, but nuget console is not the only way to do migrations, you can check this resource for some insights how to do it from code.
Now, regarding your question from question title (where they are stored?), migrations are stored in code, in a class inheriting from DbMigration class that migrations API creates for you when you do Add-Migration command in nuget console. When you perform an migration (Update-Database), either from nuget package manager console or from code, API will compare your current model with versions in __MigrationsHistory to find initial version (if you have not specified it) and perform all migrations in between initial and target version (if not specified otherwise target is latest version).
I'm not really clear how you did exclude your migration that causes problems, as you need to migrate your database to version before that migration, and then delete and recreate all subsequent migrations from there.
Maybe you could solve your fallback to old version problem by implementing public override void Down() method in your migration that causes problems when trying to rollback? This method can be used to execute code which performs inverse any operations for migration.
Not directly related to question but worth mentioning, there is also pretty detailed tutorial here for EF CF.
Anyone have a workaround (without monkey patching rails) for the failure of the db:schema:dump part of a simple migration accessing the wrong database for a table? I get the error
*Mysql::Error: View 'database1.boxscores' references invalid table(s) or column(s) or function(s) or definer/invoker of view lack rights to use them: SHOW FIELDS FROM boxscores
*
When boxscores is on database2. The ActiveRecord model is set to make the connection and the app works fine, it isjust the migration that fails, and that only b/c of the schema dump.
I am going to answer this since I found the answer and it might help someone. No one else answered, so here we go:
By adding an Active Record connect I was able to solve this issue. It also turns out that the models for those tables were not overriding the default DB connection like they should have been.
I have a standard rails application, that uses a mysql database through Active Record, with data loaded through a separate parsing process from a rather large XML file.
This was all well and good, but now I need to load data from an Oracle database, rather than the XML file.
I have no control how the database looks, and only really need a fraction of the data it contains (maybe one or two columns out of a few tables). As such, what I really want to do is make a call to the database, get data back, and put the data in the appropriate locations in my existing, Rails friendly mysql database.
How would I go about doing this? I've heard* you can (on a model by model basis) specifiy different databases for Rails Models to use, but that sounds like they use them in their entirety, (that is, the database is Rails friendly). Can I make direct Oracle calls? Is there a process that makes this easier? Can Active Record itself handle this?
A toy example:
If I need to know color, price, and location for an Object, then normally I would parse a huge XML file to get this information. Now, with oracle, color, price, and location are all in different tables, indexed by some ID (there isn't actually an "Object" table). I want to pull all this information together into my Rails model.
Edit: Sounds like what I'd heard about was ActiveRecord's "establish_connection" method...and it does indeed seem to assume one model is mapped to one table in the target database, which isn't true in my case.
Edit Edit: Ah, looks like I might be wrong there. "establish_connection" might handle my situation just fine (just gotta get ORACLE working in the first place, and I'll know for sure... If anyone can help, the question is here)
You can create a connection to Oracle directly and then have ActiveRecord execute a raw SQL statement to query your tables (plural). Off the top of my head, something like this:
class OracleModel < ActiveRecord::Base
establish_connection(:oracle_development)
def self.get_objects
self.find_by_sql("SELECT...")
end
end
With this model you can do OracleModel.get_objects which will return a set of records whereby the columns specified in the SELECT SQL statement are attributes of each OracleModel. Obviously you can probably come up with a more meaningful model name than I have!
Create an entry named :oracle_development in your config/database.yml file with your Oracle database connection details.
This may not be exactly what you are looking for, but it seems to cover you situation pretty well: http://pullmonkey.com/2008/4/21/ruby-on-rails-multiple-database-connections/
It looks like you can make an arbitrarily-named database configuration in the the database.yml file, and then have certain models connect to it like so:
class SomeModel < ActiveRecord::Base
establish_connection :arbitrary_database
#other stuff for your model
end
So, the solution would be to make ActiveRecord models for just the tables you want data out of from this other database. Then, if you really want to get into some sql, use ActiveRecord::Base.connection.execute(sql). If you need it as a the actual active_record object, do SomeModel.find_by_sql(sql).
Hope this helps!
I don't have points enough to edit your question, but it sounds like what you really need is to have another "connection pool" available to the second DB -- I don't think Oracle itself will be a problem.
Then, you need to use these alternate connections to "simply" execute a custom query within the appropriate controller method.
If you only need to pull data from your Oracle database, and if you have any ability to add objects to a schema that can see the data you require . . . .
I would simplify things by creating a view on the Oracle table that projects the data you require in a nice friendly shape for ActiveRecord.
This would mean maintaining code to two layers of the application, but I think the gain in clarity on the client-side would outweigh the cost.
You could also use the CREATE OR REPLACE VIEW Object AS SELECT tab1., tab2. FROM tab1,tab2 syntax so the view returned every column in each table.
If you need to Insert or Update changes to your Rails model, then you need to read up on the restrictions for doing Updates through a view.
(Also, you may need to search on getting Oracle to work with Rails as you will potentially need to install the Oracle client software and additional Ruby modules).
Are you talking about an one-time data conversion or some permanent data exchange between your application and the Oracle database? I think you shouldn't involve Rails in. You could just make a SQL query to the Oracle database, extract the data, and then just insert it into the MySQL database.