Is there a way to check that a DbContext matches the database when the database was not created by EF code first?
I am looking for similar functionality to Database.CompatibleWithModel but there is not metadata.
There is currently no way in EF to do this; however, you may be able to use the DDL script as a starting point for verifying that all the artifacts exist in the database. To get this script, use
string ddlScript = ((IObjectContextAdapter)myContext).ObjectContext.CreateDatabaseScript();
Some tools may be able to use this script to do a schema compare against your database. This will tell you if your model is compatible.
Have you tried using Entity Framework Power Tools.
you can use the tools to Reverse Engineer Code First - Generates POCO
classes, derived DbContext and Code First mapping for an existing
database.
And then maybe you can compare the reversed engineered information with what you already have.
Related
Trying to build an application that uses ASP.NET Authentication with Identity.
I've been watching a video on how to do things. They add new properties directly to the ApplicationUser class and then update the database using code-first migrations.
But I'm using database first.
So I added my new properties directly to the ApplicationUser class, and I also added compatible fields to my database. But I still get an error.
The model backing the 'ApplicationDbContext' context has changed since the database was created. Consider using Code First Migrations to update the database (http://go.microsoft.com/fwlink/?LinkId=238269).
I have Googled this and found articles specifically referencing database first, but they all seem to involve using code first!
Is this even possible to do without code first any more? Or is it just the case where we will all use code first or die?
As #Kyle suggested, this is all based on the __MigrationHistory table.
I'm not sure exactly how this all works, or what the overhead is if this table is being tested against my data each time I run my software. But renaming the table gets rid of the error. And I'm now able to modify the database as I wish without errors.
I've been trying to store my strings in a database using resource files to fetch them. I've been following the guide from http://afana.me/post/aspnet-mvc-internationalization-store-strings-in-database-or-xml.aspx
The example works fine enough when i use his sql code based on ADO.net to fetch the strings from the database.
But i want to use Entity Framework to fetch the strings from the database, because my translation table is quite different. Could anyone show me an example of how to use Entity Framework in the resource project(assembly?), because i can't seem to get it to work. I cant import any of my models or contexts from my main project with "using", and it tells me i have duplicate models when i copy them to the resources project/assembly
Up until now I have been using the EF Power Tools beta to do this. I click on an empty project, select EF and then reverse engineer.
The PowerTools creates all the model tables and EF mapping tables for me. It's something I do quite often when our database changes and I need to see how the mapping classes have changed. It's not completely necessary but it saves a lot of work and makes life very easy.
From what I understand is this was added to EF6.1. However where ... ?
All I see from the demos is that now I have the ability to start from a database and generate code first. For this it seems I would have to create a new application and do a lot more. I miss the two click functionality of not being able to create the mapping tables.
Does anyone know if this is still available and if I just missed it. If not available then time to go back to EF Power Tools beta :-(
Install the EF 6.1 Tools from MS downloads, and add a new "ADO.NET Entity Data Model" to your project, and you will have the new option to generate "Code First from database" https://entityframework.codeplex.com/wikipage?title=Tooling%20Consolidation
I have a database called ApplicationName_Development running on SQL Server 2008 R2 Developer edition on my development box.
I added .NET membership tables to the database with no problem. When I tried to get Code First working I received the following error message:
The server encountered an error
processing the request. The exception
message is "Model compatibility cannot
be checked because the database does
not contain model metadata. Ensure
that IncludeMetadataConvention has
been added to the DbModelBuilder
conventions.
After some googling, I discovered that I had to delete the database and let EF create the database. That's fine but I lost all my .NET membership tables. I can go back in and add the membership tables again but if my model changes and EF needs to recreate the database then I have to add the membership tables in again.
How do I get around this?
This is how code-first work. Main idea of code first is that you do not touch your database because it is responsibility of the model to create the database. If you want to customize your database you must create custom IDatabaseInitializer and add your custom SQL.
public class MyDbInitializer : DropCreateDatabaseIfModelChanges<MyContext>
{
protected override void Seed(MyContext context)
{
// Here run your custom SQL commands
context.Database.ExecuteSqlCommand("CREATE TABLE ....");
}
}
Now you only need setup your cutom intializer on the startup of your application:
Database.SetInitializer<MyContext>(new MyDbInitializer());
If you don't want to do it this way you must manually maintain your database and set initializer to null.
Found a easier workaround here. I hope this helps.
http://www.paragm.com/ef-v4-1-code-first-and-asp-net-membership-service/
Another option could be to use the System.Web.Management namespace. I've had great success with the code below:
string connectionString = ConfigurationManager.ConnectionStrings["MyDatabaseContext"].ConnectionString;
string database = "MyDatabaseName";
SqlServices.Install(database, SqlFeatures.All, connectionString);
It will just create the database and after that you can add users with the standard membership API.
Here's another possibility.
If you look at the MvcMusicStore sample - there's a SampleData class that is responsible for seeding the database on a rebuild. The SampleData class inherits from DropCreateDatabaseIfModelChanges, and overrides the Seed method. This class is passed to the Database.SetInitializer in the Application_Start method in global.asax.
I was getting the same error as you until I changed the parent class of SampleData to CreateDatabaseIfNotExist.
Then you can override the Seed method to insert any data you desire at startup, without it blowing away the database.
While you are developing, create 2 databases and two connection strings. One for SqlMembership (using aspnet_regsql) and one for your EF Application. If you would like to merge them into a single DB in production, just change the connection string in web.config.release to be the same. Then, EF model changes will just drop your apps db and not your membership DB.
By treating your authentication component separately, you will naturally decouple your authentication system from your application system. Then, if you wish to change membership providers, you will be better setup.
As the system grows, you will likely need to support non-pure models without EF code first, so this is a good template for going down that path.
I found the easiest way without playing with anything else was the following.
I ran the application first time with DropAndRecreatedatabase always in the Initilizer.
This created my database for the first time.
Following this I changed this to DropCreateDatabaseIfModelChanges.
What method do you use to get a compile time error when the database schema changes occur in an ASP.NET project?
For example, if you have a GridView bound to a DataSource, I can only get runtime errors when a schema change occurs, not a compile time error. Intellisense works fine on the code behind using datasets, LINQ, etc, but I cant seem to get a compile time error on an ASP.NET page when I change the schema.
Any advice?
Create a unit test that verifies the correctness of you data access layer, and make sure it covers all your DB-related code. Not everything can be caught at compile time...
One way I can think of easily achieving this behavior would be to databind to a dynamic DAL. There are some tools that can help do this DAL generation, I'd recommend taking a look at SubSonic.
Once you have something like SubSonic in place you can bind to the resulting business objects. These business objects will automatically change in the case of a schema change in the database and this will break your binding code which will result in a compile time error.
Update
Assaf's recommendation to use Unit Tests is also a good idea. It doesn't solve your stated problem but it is definitely something that should be in place and is a great tool for flagging these type of problems.
We use a modest system (xml to c++) to create schemas from an independent description, this system also creates names for tables and columns that we use inside the code, when there is a change in the schema the names change, as the names we originally used are not there anymore and the compiler will flag an error.
You could probably configure a lot of the DAO generation tools to do something similar.
One solution would be to version your database and map an application build to a specific version (maybe in a properties file). In the entry point of your app, you can compare the expected version to the actual version and handle the error accordingly.
I'm not sure whats the equivalent in ASP.net of Migrations in Rails or dbdeploy in Java for versioning your database. But any DB versioning tool that makes schema changes incremental and versioned and tracks the version in a Version table will suit the purpose.
But if you want a compile time error while building your app, you might as well upgrade your schema to the latest version as part of your build process, avoiding the possibility of schema changes in the first place.