I have added added Entity Framework to my project and selected Code first from database when creating my models. But the problem is, i couln't find how find how to update existing models and add new models to my project when i make changes on database.
It is very straightforward. Switch on migrations, change/add you classes, create a migration and update your database. See here for example. There are plenty of other sources.
When you change your DB you can run the EF generation again but it will overwrite the existing files so you will lose any changes. If you want to maintain code outside the generated files then you can use partial classes. Or alternatively just code them by hand after the initial auto generation, it's quick once you get used to it! :)
Related
I am new to Entity Framework 6 Code First and am trying to perform what I thought would be a simple task. I want to create a SQL View and then have an Entity in my database context that I can use to query the view.
I have tried articles such as this but the key difference in my case is that the SQL View is not an existing view coming from another existing database.
I examined the proposition made in this article but it seems like overkill to me that I would need to create some extension methods to do something as simple as create a view/entity combo and use it in my database context.
Am I missing something? I know it would be much easier if I weren't using Code First but please keep in mind it's Code First and I am trying to create a view, not reuse one from an existing database.
Colin and Kevin, Thank you for the link to your answer on the other post and your concise answer. I have used several resources to finally create a queryable entity based on a new SQL view. Just in case anyone else is new to EF 6.0 Code First and is just getting their feet wet, I do have a few steps that will hopefully benefit others in the future.
It may seem obvious to more seasoned Entity Framework developers, but in order to execute the 'Migration' approach you need to disable automatic migrations and actually dive into the guts of the Code First Migrations inner workings. Since automatic migrations is turned on out of the box, I had already created a fairly complex database with seed scripts all relying on automatic migrations and rebuilding the database on every run of my application. This post helped me wipe my migrations history and get to square 1 with automatic migrations turned off (I went with the web.config approach in case you were wondering)
After I had cleared my migrations information, I deleted the mdf from within solution explorer. That guaranteed that I wouldn't run into any problems when running Update-Database (further down the list of steps).
In the Package Manger console, I then executed Add-Migration Initial to generate an "Initial" migration. The result of this was the editable Up and Down methods as described in Colin's answer. I then followed the steps in Colin's answer by commenting out the table create statement (Entity Framework tries to create a table but we really want to create a view and map it to the Entity) and inserting my own view create sql statement at the end of the Up method. It's important to put the create statement after the creation of any tables that it may depend on. I also performed my Seed activities in the Configuration.Seed method instead of in my Context's Seed method. I see how this would be important if you were dealing with multiple migrations. Finally, as Colin suggested I added the table mapping to my context's OnModelCreating event.
The final step in this was to actually apply the migration to the database. In order to do that, in the Package Manager console you execute the Update-Database command. That statement will rebuild the database with the "Initial" migration you created and edited in earlier steps.
It still surprises me that I need to do all of this custom work to create a view and map it to an entity with Code First, but at the end of the day it was helpful in getting me started on migrations as you can only rely on the "automatic migrations" for so long anyways.
You can manually add the sql to create the view to a migration then consume it as per your first link.
The answer in the link provided by Colin does the job.
In case there are lots of views to be created, it can be a good idea to save the view queries in separate files and add them in a resource (.resx) file instead of hard-coding the sql queries in the Migration Up() method.
For e.g.
public override void Up()
{
Sql("ResourceFileName.ResourceName");
}
instead of hard coding like
{
Sql("EXEC ('CREATE View [dbo].[ClientStatistics] AS --etc");
}
Using Entity Framework 6 Code First in an ASP.NET project with Visual Studio 2013, is there any way to rebuild (or update) the generated DataContext and model classes without stepping through the Entity Data Model Wizard every time?
I'm fully aware of how to do this with an EDMX designer, but again, I'm using the "Code First from database" method and just wondering if there's a one-click (or one console command) way to trigger the rebuild without having to delete the generated context class and then step through the Entity Data Model Wizard every time I make a change to the backing database.
In VS 2015 (and supposedly 2013/2012) you can use the Entity Framework Reverse POCO generator to accomplish this.
https://visualstudiogallery.msdn.microsoft.com/ee4fcff9-0c4c-4179-afd9-7a2fb90f5838
You can make all your changes to database first, and to re-generate your models all you have to do is save your Database.tt file (usually I just add white space).
Code first requires you to create the DataContext by hand. You don't create/change the database and refresh the DataContext class. The Code first from database or EF Reverse POCO template is a middle ground between true Code First and the Database First approach of doing things. It meets at the middle by generating the same kind of POCO classes that you would have written by hand in Code First. They don't do it in Code First way but the end result is something similar to Code First. Hence the confusing name.
If you are using one of these templates to generate POCOs, you can right click on the t4 template file and click Run Custom Tool. If that doesn't work, you might want to delete that entity and then run the custom tool again. Also right clicking on the EDMX and clicking 'Update Model from Database' should work.
I have the solution for rebuild without wizard:
using the t4 is Transform All T4 Templates
and create the classes
Trying to grasp the big picture here. This is a Web Forms project using Identity + EF for user management. The default project contains IdentityModels file which suggests that I should add custom properties to ApplicationUser class and then use migrations to update my database. I did that and the database was generated/updated. So far so good.
Now I add a new EDMX to my project and import all my DB tables into it. This obviously brings in Identity tables into the diagram as well, which is good because I'll be adding my business domain tables and linking them to Identity tables through the model and then use migrations to update my database. Here are the questions and problems I face:
Am I using Code-First or Model-First, or a mix of both (Does such a mix work)?
Do I have more than one model in my project, namely the default Models file and the one generated by EDMX?
If I have two models, which of the model classes correspond to AspnetUsers table; the default ApplicationUser class or the AspNetUser class generated by the EDMX? I mean which of these classes will be used by migrations to update my table's structure?
Adding new properties to my ApplicationUser class doesn't seem to have any effect when I run Add-Migration and Update-database commands. It generates empty Up() and Down() functions.
Adding a new property to an EDMX entity and then trying to send it to the database through migrations throws error saying that the new property doesn't have a mapping column. Now that's obvious I know, but then how does Model-First approach send changes to the DB?
I know these are more than one questions, but they are tightly related and anyone trying to get a start will most probably face all of them, so I've gathered them in one place for future readers.
In my understanding using both EF Code-First and Model-First can add a burden of keeping them in sync. You may want to check the following sample project which uses only DbFirst approach:
https://github.com/kriasoft/AspNet-Server-Template
OK. After working with the project for a few days, I have figured out a few things that might be helpful for future readers:
As #Konstantin said, as a general rule, you should not use both code-first and model-first approaches in the same project. Personally I prefer database-first over both of them, i.e. create a database design and then import it into my EDMX model. I can then make changes to my DB design later and use "Update Model from Database..." command to refresh my model.
AFAIK, migrations cannot currently be used with EDMX models. These only work with code-first approach.
ASP.NET Identity will automatically create all required tables in your database when your website runs for the first time. You simply need to correct the connection string in your web.config file.
You should generally avoid bringing in Identity tables into your EDMX, but if you really need to do that, do not make changes to these entities through EDMX. Simply use ApplicationUser class in IdentityModels file to add custom properties to your user class.
In a class library Ado.net Entity Data Model is has generated POCO classes. These were generated fine for the first time. But database changes are not being reflected. In edmx diagram right clicking and choosing Update Model from Database show newly created table but it do not add table even after selecting it to add.
I tried running .tt (by right click and Run custom tool) but even it did not regenerated the Poco classes as per latest DB changes.
Help please
Not a fix but a workaround: Is it not an option to simply remove and regenerate the EDMX and the generated classes? That's what I do, it is much easier than working with the update feature, and the result seems to be the same. Your POCO extensions still remain the same and functional.
I use database first and I have my SQL upgrade scripts, the generated EDMX and my Generated models in source control and the changes there are very easy to manage. Here is a rough outline of my DB upgrade process for each version:
Create .sql script for the upgrade, statements like CREATE TABLE etc.
Delete generated files: Model.Context.tt, Model.tt, Model.edmx
Remove Entities string from Web.config (if you use it)
Create the EDMX and Context files the same way you did for the first time
If you use source control (I hope you do!) check what has changed
Test
Commit!
In my case i needed to save ModelName.edmx, then classes were generated.
Ensure that connections string in app.config is correct. I was using a DataDictionary and my connection string had the following path:
data source=|DataDirectory|*.sqlite
Thus, it wasn't updating. Because this DataDirectory variable was being resolved at runtime.
Now that i have generated 19 code-first classes from an existing database by:
Creating a Model-First Entity, and choosing "Generate from database"
Right clicking and choosing "Add Code Generation Item"
EF 4.x DbContext Generater
All the classes i want are generated, and I'm very happy with them...
And now for my question(s)
Why are they all the generated .cs files nested in a sealed .tt collection?
Why can't i copy paste them out to any folder i like, and treat them like normal classes?
Is it just me, or are you unable to use migrations "update-database" when you do it like that?
I guess my overall question is, why are they located in a .tt folder?
And how shall i update my database now? By editing the database manually and then update the Model, and then generate the dbContext again? Or is there a trick to get .cs files out of a .tt folder?
How do you modify you database after generating your DbContext?
Why are they all the generated .cs files nested in a sealed .tt collection?
Your code-first classes are not code-first classes. They were generated based on your database schema. Hence, this is a database-first approach. With database first, your entity classes are generated based on the database. In other words, the database comes first, the code comes second. The .tt file is a T4 template that decides how to generate your classes based on the database. You could change the database and then regenerate your entity classes.
Why can't i copy paste them out to any folder i like, and treat them like normal classes?
Because they are generated files, based on the T4 template.
Is it just me, or are you unable to use migrations "update-database" when you do it like that?
This part of your question I can't answer for certain, and will have to defer. However it seems to me like you want to mix and match approaches. It sounds like you want to start by generating code classes based on your database, and from there forward, change the database based on new entity classes you add to the model project. Is that right?
You can forgo the code-generation part and just go with a pure code-first approach, now that you have an idea of what the entity POCO's should look like. I have tried this T4 code generation before (pre EF 4.1) and immediately abandoned it, because as you have seen, since the entity and DbContext classes are generated, you lose control over the object-oriented model.