When I used TPH, all the tables recreated - entity-framework

I am developing an EF - MVC 3 application. I have used model first approach, so I have create model first and from that model, EF generated the DB.
I have used a tool called Nuget - Entity Generator - Database designer for generating the database. When I have designed the model first time, I have used the Generate Migration T-SQL and Deploy option of that tool.
Database generated perfectly and it's working fine...
Now I have come across a situation that I have to make a change to the model and I have to use T-SQL Via T4 (TPH) option to update the database.
So previously I used different process to update DB and now I am changing it.
When I use the T-SQL Via T4 (TPH) all the tables get deleted and new tables get created.
How to avoid this ?
I want to only update the table which I have made the changes.

Entity framework 4.3 comes with migration support. This is not available in EF 4.1.
Some links from google:
http://blogs.msdn.com/b/adonet/archive/2012/02/09/ef-4-3-automatic-migrations-walkthrough.aspx
http://blogs.msdn.com/b/adonet/archive/2012/02/09/ef-4-3-code-based-migrations-walkthrough.aspx

Related

Development process for Code First Entity Framework and SQL Server Data Tools Database Projects

I have been using Database First Entity Framework (EDMX) and SQL Server Data Tools Database Projects in combination very successfully - change the schema in the database and 'Update Model from Database' to get them into the EDMX. I see though that Entity Framework 7 will be dropping the EDMX format and I am looking for a new process that will allow me to use Code First in Combination with Database Projects.
Lots of my existing development and deployment processes rely on having a database project that contains the schema. This goes in source control is deployed along with the code and is used to update the production database complete with data migration using pre and post deployment scripts. I would be reluctant to drop it.
I would be keen to split one big EDMX into many smaller models as part of this work. This will mean multiple Code First models referencing the same database.
Assuming that I have an existing database and a database project to go with it - I am thinking that I would start by using the following wizard to create an initial set of entity and context classes - I would do this for each of the models.
Add | New Item... | Visual C# Items | Data | ADO.NET Entity Data Model | Code first from database
My problem is - where do I go from there? How do I handle schema changes? As long as I can get the database schema updated, I can use a schema compare operation to get the changes into the project.
These are the options that I am considering.
Make changes in the database and use the wizard from above to regenerate. I guess that I would need to keep any modifications to the entity and/or context classes in partial classes so that they do not get overwritten. Automating this with a list of tables etc to include would be handy. Powershell or T4 Templates maybe? SqlSharpener (suggested by Keith in comments) looks like it might help here. I would also look at disabling all but the checks for database existence and schema compatibility here, as suggested by Steve Green in the comments.
Make changes in code and use migrations to get these changes applied to the database. From what I understand, not having models map cleanly to database schemas (mine don't) might pose problems. I also see some complaints on the net that migrations do not cover all database object types - this was also my experience when I played around with Code First a while back - unique constraints I think were not covered. Has this improved in Entity Framework 7?
Make changes in the database and then use migrations as a kind of comparison between code and the database. See what the differences are and adjust the code to suit. Keep going until there are no differences.
Make changes manually in both code and the database. Obviously, this is not very appealing.
Which of these would be best? Is there anything that I would need to know before trying to implement it? Are there any other, better options?
So the path that we ended up taking was to create some T4 templates that generate both a DbContext and our entities. We provide the entity T4 a list of tables from which to generate entities and have a syntax to indicate that the entity based on one table should inherit from the entity based on another. Custom code goes in partial classes. So our solution looks most like my option 1 from above.
Also, we started out generating fluent configuration in OnModelCreating in the DbContext but have swapped to using attributes on the Entities (where attributes exist - HasPrecision was one that we had to use fluent configuration for). We found that it is more concise and easier to locate the configuration for a property when it is right there decorating that property.

auto update code first from database model, is it possible?

I have code first classes which are generated from my existing db using ADO.NET Entity Data Model. Now I've added some new tables to the database.
I want to know if its possible to create associated code classes from the new db tables without (re)creating the model again from scratch?
Yes it is, if you use Reverse Engineer Code First to do so. It will create POCOs exactly like Code-First, but it will do so based completely on the current database. No .edmx file and no T4 template. Just Code-First.
You should know, by the way, that this (along with regular Code-First) are going to be the only ones allowed in EF7. They are getting rid of many things to try to slim it down, and both Model- and Database-First got the ax (at least, for now). This blog post from Microsoft's ADO.NET blog explains that, along with some other features.

Entity Data Model Wizard not creating tables in EDMX file

I'm trying the database first approach by creating an ADO.NET Entity Data Model using the wizard with the Adventureworks2012 DB.
Testing DB connection works, and the connection string is added to the App.Config.
I'm selecting all the tables except the ones marked as (dbo) AWBuildVersion, DatabaseLog, and ErrorLog.
When the wizard finishes the .edmx file is blank, and if I view the file in XML view the EntityContainer is empty.
After the model is created it returns this error in the output window:
Unable to generate the model because of the following exception: 'The
table AdventureWorks2012.Production.Document is referenced by a
relationship, but cannot be found.
I'm using VS 2010 & .NET Framework 4.0
It seems that Entity Framework does not know how to deal with data types like hierarchyid set on a table field. I removed the Production.Document table for the list of entities to include solving my problem.
Note also that this reference below was for Adventureworks 2008R2 with EF version 1.0 from Code Plex SQL Sever, and I am using Adventureworks 2012 from the same CodePlex site using EF version 4.4.
Reference: http://msftdbprodsamples.codeplex.com/wikipage?title=AW2008Details
Note: EF 1.0 Compatibility Issues
The Entity Framework team would like us to let you know that AdventureWorks2008 is a little bit ahead of the curve in terms of the Katmai features it uses. Some datatypes in AdventureWorks2008 (such as hierarchyid and geometry) are not supported in the entity framework. The workaround is to exclude tables like Production.Document from your model if possible since there is currently no support for the hierarchyid datatype in Entity Framework 1.0. Unfortunately the Entity Framework tooling which updates your model from the database will pull in tables like Production.Document even if they were specifically excluded when the model was created, so use of that feature on AdventureWorks2008R2 is not supported at this time. We look forward to a follow-on release of Entity Framework which has full SQL Server 2008 type support.
Last edited May 25, 2010 at 2:22 PM by bonniefe, version 17
There is a way to get around this IF you're trying to learn from this example and not doing anything meaningful. I deleted the foreign keys to the offending table and removed it and was able to succesfully get
Uncheck [Allow Nulls] Check-boxes (in the table design) for all the foreign keys of the not created Tables (Tables not converted to the model).
Then you can update your model to retrieve those tables by doing the following steps:-
Step 1 - Right click some where in your .EDMX file's design (i.e. Model1.EDMX [Diagram1].
Step 2 - then from the Context Menu select / Update Model from Database....
Step 3 - then select "Add"
Step 4 - then expend "Tables" Check-Boxes and select your desired tables (tables not created first time).
Step 5 - then click Finish button.
Step 6 - Save the the solution and hope everything will be Ok.
Note: I'm using Visual Studio 2013.
Good luck.

Entity Framework 4.3 migrations on existing "Shared" database

We have a huge database with different database schemas for different web applications.
For example: WebApp1 uses Schema1.Tables. WebApp2 uses Schema2.Tables and so on.
Now, I am developing a new web application (WepApp3) which will use Entity Framework 4.3.1. WebApp3 should only be concerned with Schema3 and use only those database object which are part of Schema3. If i create some Entities in WepApp3, How do i migrate these entities to database as schema3.tables? Do i still need to do Initial Migration?
Please help.
I don't think it's possible to have multiple EF models in the same database. EF shouldn't try to touch tables that are nothing to do with its model, but if you wanted to add another EF app to the same database you'd run into trouble because they'd try to share the same MetaData tables.
When generating new models using code-first, you can specify which schema they should be part in the DbContext:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<MyEntity>().ToTable("MyEntity", "Schema3");
}
Is it an option to migrate your schemas out into different databases if there are no shared apps?
It seems to WORK. I started with an existing database. created an mvc app (app1) with couple of models. I then created a schema for this app in database. I specified schema for the models as per your comment. Then I used the power of code based migration script to update the database. Migration script created 2 tables under the new schema without corrupting existing stuff. I noticed EF created __MigrationHistory table with a row with change info.
Then i created another app, a new schema and repeated the migration process with a little tweak in migration script. The script had code to re-create 2 tables of app1. i deleted that code from script. EF then successfully created new tables under new schema and also created new row in __MigrationHistory table with info about new changes. All existing stuff remain unchanged including data.

Building DB schema from Entity Framework Model

I see that EF can update a model based on an existing database schema. However, I'm starting totally from scratch; I don't want to build tables, then rebuild them in the EF model file. Is there a way that I can draw out a model file, and have the SQL tables automatically be created for me?
Unfortunately, you have to wait for version 2 of EF.
Here is a link to the EF team's blog, where they talk about adding Model First support in v2:
One of the most painful omissions from the Entity Framework V1 was Model First, which basically means creating a conceptual 'model first' and then deriving a storage model, database and mappings from that.
[...]
The next release of the Entity Framework will include the ability to generate database schemas from your model. The main entry point into this feature is via the Designer context menu, to which we will add a new option called “Create Database from Model”.